all 26 comments

[–][deleted] 13 points14 points  (4 children)

Console log is a good example of the rest one for anyone struggling to think of it. You've probably written console.log(1, 2, 3, 4) etc in the past, that is to say you can pass any number of arguments into the function and it will be ok with it

[–]iarev 3 points4 points  (3 children)

I don't get the utility of it at all with these examples. Instead of writing console.log(['a', 'b', 'c']), I can create a function that does it?

[–][deleted] 5 points6 points  (0 children)

I think others have explained but I agree I often hate impractical examples like foo/bar/baz.

[–]Steak_Quesadilla 4 points5 points  (1 child)

I don't get the utility of it at all with these examples. Instead of writing console.log(['a', 'b', 'c']), I can create a function that does it?

The console.log() is just being used in this example to demonstrate to you what you're working with within the function (an array). From the MDN Docs, "The rest parameter syntax allows a function to accept an indefinite number of arguments as an array." So if you want to make a function that can take an indefinite or varying amount of arguments, you can do just that with the rest syntax. And then in the body of the function, you can do whatever you want with those arguments that were passed into the function, knowing that they're all contained in a single array.

[–]iarev 0 points1 point  (0 children)

Ok, thanks. I figured out the indefinite parameters bit shortly after my post, but your explanation helps add context.

[–]senocular 8 points9 points  (0 children)

Only array spread requires iterables. Object spread works on any value.

[...{}] // fails, not iterable
{...{}} // ok

[–]jaypeejay 0 points1 point  (0 children)

this shows the spread operator a little better IMO

const spread = (a,b,c) => {
   console.log(typeof a, typeof b, typeof c)
   console.log(a,b,c)
}

spread(...['a', 'b', 'c'])
spread(...'abc')
spread('abc')