Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I remove the intermediate variable in my code?

I'm currently working with the spread syntax and ran into an unexpected issue.

The below snippet works (as expected), and doesn't throw any errors:

const arr = [1, 2, 3, 4] // create array of numbers

const copy = [...arr] // make a shallow copy of the array
copy.forEach(n => { // loop through array
  console.log(n + 1);
});

However, if I remove the intermediate variable copy, my code seems to throw an error:

const arr = [1, 2, 3, 4] // create array of numbers

[...arr].forEach(n => { // loop through array
  console.log(n + 1);
});

As you can see, the above code snippet throws an error:

Uncaught SyntaxError: Unexpected token ...

Whereas the first snippet does not. Why is this happening? To my understanding I should be able to replace copy with literal array it contains and have no issues (as I have done in the second snippet).

I expect the second snippet to behave as the first snippet, and not throw any errors.

Note: I'm aware that [...arr] seems redundant in this case, I've simply used this to demonstrate my problem.

like image 936
Shnick Avatar asked Jun 16 '26 06:06

Shnick


1 Answers

Add a semicolon and it works perfectly.

const arr = [1, 2, 3, 4];

[...arr].forEach(n => {
  console.log(n + 1);
});

The code was being evaluated without the newline - like this:

const arr = [1, 2, 3, 4][...arr]

Which resulted in your error.

like image 57
Jack Bashford Avatar answered Jun 17 '26 18:06

Jack Bashford



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!