Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Example :

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

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

like image 795
PhilipGarnero Avatar asked Nov 13 '17 11:11

PhilipGarnero


People also ask

How do you Destructure an array of objects es6?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element. const [var1, var2, ...]

How do you swap variables using Destructuring assignment?

Destructuring assignment[a, b] = [b, a] is the destructuring assignment that swaps the variables a and b . At the first step, on the right side of the destructuring, a temporary array [b, a] (which evaluates to [2, 1] ) is created. Then the destructuring of the temporary array occurs: [a, b] = [2, 1] .

What is object and array Destructuring in JavaScript with es6?

Destructuring means to break down a complex structure into simpler parts. With the syntax of destructuring, you can extract smaller fragments from objects and arrays. It can be used for assignments and declaration of a variable.

Can you give an example of Destructuring an object or an array?

In the first line, we are declaring a new variable studentsArr , and assigning it the value of an array of student names. Line 2 is where we destructure. In line 2 we declare three variables; first , second , and third . By declaring them on the left-hand side, we initiate destructuring.


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; 
like image 122
kind user Avatar answered Oct 12 '22 01:10

kind user


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

like image 35
drazewski Avatar answered Oct 12 '22 02:10

drazewski