Reputation: 187
I am new to Javascript and is confused why the following won't work?
var array = [1, 2, 3, 4]
var spread = ...array;
I was expecting it would become 1, 2, 3, 4
. Instead, it gave an error message Unexpected token ...
. Can anyone explain this to me?
Thank you so much!
Upvotes: 0
Views: 1204
Reputation: 30739
The syntax for using spread
is:
For function calls:
myFunction(...iterableObj);
For array literals or strings:
[...iterableObj, '4', 'five', 6];
For object literals (new in ECMAScript 2018):
let objClone = { ...obj };
So, based on the syntax, for an array by using spread
you are missing the square brackets []
:
var array = [1, 2, 3, 4]
var spread = [...array];
console.log(spread);
Upvotes: 1
Reputation: 33726
This is the correct way, however you're not gaining anything doing that.
var array = [1, 2, 3, 4]
var spread = [...array];
console.log(spread);
If you really want to destructure that array, you need destructuring assignment:
var array = [1, 2, 3, 4]
var [one, two, three, four] = array;
console.log(one, two, three, four);
Upvotes: 3
Reputation: 146
The correct way of doing what you want is:
var array = [1, 2, 3, 4]
var spread = [...array];
Upvotes: 1