RamKris
RamKris

Reputation: 115

Understanding ES6 to ES5 code as transpiled by Babel

Babel transpiles the following ES6 code

test(){
    var list = [ 1, 2, 3 ]
    var [ a, , b ] = list
    [ b, a ] = [ a, b ]
  }

into this

function test() {
      var list = [1, 2, 3];

      var _list = list[(b, a)] = [a, b];

      var _list2 = _slicedToArray(_list, 3);

      var a = _list2[0];
      var b = _list2[2];
    }

I can't understand what exactly is happening with this line of code

var _list = list[(b, a)] = [a, b];

Specifically, I am clueless with list[(b, a)]. Any help is much appreciated?

Upvotes: 2

Views: 189

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161657

The short answer is that

var [ a, , b ] = list
[ b, a ] = [ a, b ]

is the same as

var [ a, , b ] = list[ b, a ] = [ a, b ]

because automatic semicolon insertion does not apply to this situation. The same case applies to this ES5 example:

var list = [1, 2, 3]
var value = list
[1]
console.log(value);

If you run this code, it will log 2, not [1, 2, 3] because the index is applied to the previous line, rather than treated as an array on the following line.

Automatic semicolon insertion generally applies in cases where the parser encounters a syntax error, goes back a step, and tries after inserting a semicolon.

In both of these cases, the content of the following line is perfectly valid as part of the previous line, so it is treated as such with no automatic semicolon.

In your example, list[a, b] is parsed as accessing an index using the result of comma-operator operation, which will essentially evaluate to list[b]. The comma operator processes a list of expressions one at a time, and then finally evaluates to the result of the last expression.

Upvotes: 2

Related Questions