Javascript allows swapping of variables:
var x = 1
var y = 2
[x, y] = [y, x] // y = 1 , x = 2
And destructured assignment:
var a, b
[a, b] = [1, 2]
log(a) // 1
log(b) // 2
When using variable swapping in lieu with destructured assignment, trying to swap variables breaks down:
var a, b
[a, b] = [1, 2] // a = 1, b = 2
[a, b] = [b, a] // TypeError: Cannot set property '2' of undefined
Why is that?
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 Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables.
Method 3: One Liner Using DestructuringWe could use the destructuring to swap the two elements in an array.
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
If you decide to omit semicolons (no judgement, I prefer it that way too), don't forget to prefix lines beginning with array literals with ;
. Occasionally, semicolon insertion does matter, because it might not occur when you want or expect it to.
var a, b
;[a, b] = [1, 2]
;[a, b] = [b, a]
console.log(a, b)
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