How to mix const and let when using object or array destructuring assignment in ES6?

Viewed 14539

Example :

const foo = {a: "A", b: "B"}
const {a, b} = foo

What if I want b to be a variable using let ?

2 Answers

It seems like you can't differentiate variable's declaration in a one line. However, you could split it into two lines and use a different variable declaration, depends on which variable you want to get.

const { a } = foo; 
let { b } = foo;

If you want to use array destructuring assignment with const and let you can use elision. Let's consider an example:

const [a, b, c] = foo;

If you want to 'a' be a let, and 'b' and 'c' const, you can write:

let [ a ] = foo;
const [, b, c] = foo;

Another way is to use the fact that array is an object. So you can write it also like this:

let [a] = foo;
const {1: b, 2: c} = foo;

All about destructing can be find here: http://exploringjs.com

Related