geekydude703
geekydude703

Reputation: 187

Spread syntax doesn't work to destructive an array

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

Answers (3)

Ankit Agarwal
Ankit Agarwal

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

Ele
Ele

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

Lucas Lago
Lucas Lago

Reputation: 146

The correct way of doing what you want is:

var array = [1, 2, 3, 4]
var spread = [...array];

Upvotes: 1

Related Questions