es6-features icon indicating copy to clipboard operation
es6-features copied to clipboard

The result of Array Matching is wrong

Open jasonkim7288 opened this issue 4 years ago • 2 comments

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 avatar Oct 02 '20 01:10 jasonkim7288

@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 ];

kamil-kielczewski avatar Nov 01 '22 08:11 kamil-kielczewski

If we are so obsessed with writing code in one line using spread operators: var [b, ,a] = [a, ,b] = list

aziyatali avatar Nov 01 '22 08:11 aziyatali