Why can't spread operator be used multiple times?
let arr = [[[1, 2, 3]]];
console.log(arr); // Array [ Array[1] ]
console.log(...arr); // Array [ Array[3] ]
console.log(...(...arr));
// SyntaxError: expected '=>' after argument list, got ')'
I would expect:
console.log(...(...arr)); // Array [ 1, 2, 3 ]
The spread operator is a new addition to the set of operators in JavaScript ES6. It takes in an iterable (e.g an array) and expands it into individual elements. The spread operator is commonly used to make shallow copies of JS objects. Using this operator makes the code concise and enhances its readability.
Then the spread syntax inside of it allows you to perform a check, if userCanDecline evaluates to true, it returns another array of objects, otherwise it returns an empty array.
Using the spread operator to overwrite an object property It's a super clean syntax and easy to see which value we are overwriting. The only thing you must remember while using this method is that the order matters. If we, for instance, put the property we want to overwrite.
Why can't spread operator be used multiple times?
...
is not an operator. (...arr)
is not valid JavaScript. ...
is only allowed inside array literals and in arguments lists, but those are special forms of the syntax (notice the ...
in the production rules below).
ArrayLiteral
ArrayLiteral :
[ Elision_opt ]
[ ElementList ]
[ ElementList , Elision_opt ]
ElementList :
Elision_opt SpreadElement
ElementList , Elision_opt SpreadElement
SpreadElement:
... AssignmentExpression
Arguments
Arguments :
( )
( ArgumentList )
ArgumentList :
AssignmentExpression
... AssignmentExpression
ArgumentList , AssignmentExpression
ArgumentList , ... AssignmentExpression
According to this, spread syntax input is an iterable (e.g. array), but its produce output which is non-iterable (e.g. non-array). So the problem is that in outer spread syntax ...
as input you put non-iterable thing (...arr
) which cause SyntaxError. To flat you array you can use flat (if you put Infinity instead 2, then you will flat any nested array)
arr.flat(2)
let arr = [[[1, 2, 3]]];
console.log(arr.flat(2));
let arr2 = [[1,2,[3,4,[5,[6]]]], [[7,[8]],9]];;
console.log(arr2.flat(Infinity));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With