Example :
const foo = {a: "A", b: "B"} const {a, b} = foo
What if I want b
to be a variable using let
?
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, ...]
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] .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With