59

Example :

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

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

PhilipGarnero
  • 2,399
  • 4
  • 17
  • 24

2 Answers2

57

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;
kind user
  • 40,029
  • 7
  • 67
  • 77
31

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

drazewski
  • 1,739
  • 1
  • 19
  • 21