Y.X
Y.X

Reputation: 61

How to understand this syntax? [a, b] = [b, a]?

In a sense, I know it is a syntax maybe from es6 that change the position of a and b, but I wonder is it elegant to web fronted programmer? And is it necessary to replace intermediate variables like:

var a=3,b=5;
var temp;

temp = a;
a = b;
b = temp;

to this:

var a = 3,b = 5;
[a,b] = [b,a];

And what difference between them on performance?

Upvotes: 1

Views: 1669

Answers (1)

Brian Adams
Brian Adams

Reputation: 45830

Both are valid ways of swapping variables.

Destructuring requires less code and could be considered a more elegant approach, but it looks like it is currently slower than using a temp variable:

const startTempVariable = new Date();
for (let i = 0; i < 100000000; i++) {
  var a=3, b=5;
  var temp;
  temp = a;
  a = b;
  b = temp;
}
console.log(`temp variable: ${new Date() - startTempVariable}ms`);

const startDestructuring = new Date();
for (let i = 0; i < 100000000; i++) {
  var a=3, b=5;
  [a,b] = [b,a];
}
console.log(`destructuring: ${new Date() - startDestructuring}ms`);

Both approaches are quite fast, though, so for most web programming scenarios either approach would be fine.

If you are coding something for performance you would currently want to use a temp variable.

Upvotes: 1

Related Questions