Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using spread operator multiple times in javascript?

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 ]
like image 776
madox2 Avatar asked Jan 26 '16 17:01

madox2


People also ask

Does spread operator work in JavaScript?

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.

Does spread operator return new array?

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.

Does spread operator overwrite?

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.


2 Answers

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
like image 144
Felix Kling Avatar answered Sep 22 '22 15:09

Felix Kling


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));
like image 33
Kamil Kiełczewski Avatar answered Sep 23 '22 15:09

Kamil Kiełczewski