es6-features
es6-features copied to clipboard
The result of Array Matching is wrong
The result from ES6 Array Matching is not what it is expected to be with syntactic sugar which is the default.
var list = [ 1, 2, 3 ]
var [ a, , b ] = list
[ b, a ] = [ a, b ]
The result is supposed to be a is 3 and b is 1, but due to the syntactic sugar, a and b are all undefined. That is because the code will be like
var [ a, , b ] = list[ b, a ] = [ a, b ]
Therefore, I just put square brackets for the last sentence.
@jasonkim7288 Good question - but this is not SYNTAX SUGAR. Your example shows why you should allways use semiclon ;
at the end of the line (because it is easy to miss place where JS join lines). Below code works as expected
var list = [ 1, 2, 3 ];
var [ a, , b ] = list;
[ b, a ] = [ a, b ];
If we are so obsessed with writing code in one line using spread operators:
var [b, ,a] = [a, ,b] = list