getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
Other
177.97k stars 33.41k forks source link

Spread operator can also spread into objects #1712

Closed david-shortman closed 3 years ago

david-shortman commented 3 years ago

I already searched for this issue

Edition: 2nd Book Title: You Don't Know JS

Chapter: 3

Section Title: Consuming Iterators

Question: The section describing the spread operator states that it can only be used to "spread into" . ECMAScript 2018 specifies that it can be used in objects as well. Am wondering if this emission is purposeful to focus on an earlier version?

getify commented 3 years ago

It's a tricky little nuance of the way JS works, but technically ... inside an object literal is not the same kind of "spread" as when you see that inside an array. Indeed, the ... in an object literal is not consuming an iterator (the point of this chapter section), it's actually using a different mechanism entirely, where it copies over an object's keys. This is a different protocol with different terminology, so it's referred to as "object spread" instead of "spread" or "iterator spread".

david-shortman commented 3 years ago

Ah, didn't know the distinction!

It's almost cool enough to warrant a passing mention there, then to be elaborated in a different chapter... but either way, it's clearly not an iterable procedure.

getify commented 3 years ago

Yeah, since this is the beginner/entry-level book, I had to make some tough choices into which weeds to get into or not. I didn't want to tackle nuance like that here, but I do acknowledge that it could trip someone up if they're already aware of object spread but not aware that it's a different kind of thing (as you were). Thanks for the feedback.