Why have the three dots syntax?

So basically I don’t get what’s the difference between these two lines:

[...cars].forEach((car) => console.log(car));

AND

cars.forEach((car) => console.log(car));

Yes, those are silly examples. They do the same things (as far as I can tell) making the first one look silly. But the rest and spread operators are incredibly powerful tools in the real world. I use them all the time. There probably isn’t anything you can do with them that you couldn’t do without them, it would just get very messy.

1 Like

Can you provide an example from one of those real world situations ?

Thanks!

One easy use of of the spread operator is creating a unique copy.

const arr1 = [1, 2, 3];
const arr2 = arr1;
arr1[0] = 'apple';
console.log(arr1);
// ["apple", 2, 3]
console.log(arr2);
// ["apple", 2, 3]

const arr3 = [1, 2, 3];
const arr4 = [...arr3];
arr3[0] = 'banana';
console.log(arr3);
// ["banana", 2, 3]
console.log(arr4);
// [1, 2, 3]

In the first one, all we’ve done is copied the address of the array, not made a unique copy. This becomes very useful with things like redux. There are other ways to combine this with other things to make life easier.

Another option is to convert an array into a list of arguments. Consider the differences here:

const arr = [1, 2, 3];
console.log(arr);
// [1, 2, 3]
console.log(...arr);
// 1 2 3

There are similar operations you can do with objects. And there is also the rest operator that looks like the spread operator but because of context does something different.

Again, these are things I could do with different means, but it would get uglier and more difficult to read. The spread operator (once you’re used to it) is a very powerful tool. I use it all the time.

Don’t worry about it too much. Just learn the basics. As you start coding you’ll get a sense of these things. But there isn’t much in these lessons that won’t be useful at some point.

1 Like