Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring assignment and variable swapping

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?

like image 296
jottr Avatar asked Mar 02 '17 18:03

jottr


People also ask

How do you swap variables in 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 are Destructuring assignments?

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.

Can you use array Destructuring to swap elements in an array?

Method 3: One Liner Using DestructuringWe could use the destructuring to swap the two elements in an array.

What is Destructuring assignment in es6?

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.


1 Answers

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)
like image 75
gyre Avatar answered Oct 03 '22 07:10

gyre