Search code examples
javascriptjavascript-1.7

Javascript. Swap two variables. How it works?


Saw in a single source next:

[param_o,param_got] = [param_got,param_o];

This code swap variables param_o & param_got.But how [param_o,param_got] = [param_got,param_o] works, if [] is new instance of Array in Javascript ?

EDIT Try checking:

var param_o = 1;
var param_got = 2;
[param_o,param_got] = [param_got,param_o];
console.log(param_o+" "+param_got);

// 2 1

Solution

  • This notation is called destructuring assignment and is part of Javascript 1.7:

    Destructuring assignment makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

    The object and array literal expressions provide an easy way to create ad-hoc packages of data. Once you've created these packages of data, you can use them any way you want to. You can even return them from functions.

    One particularly useful thing you can do with destructuring assignment is to read an entire structure in a single statement.

    The first sample actually demonstrates explicitly that this is useful to avoid temporary variables as in your code sample.

    Firefox has supported this feature since Firefox 2 already. For Chrome the bug is still open after 3 years. IE11 doesn't support it either from what I've just tested.