getify / You-Dont-Know-JS

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

`Symbol.isConcatSpreadable` can only work on Array object? #1732

Closed OahMada closed 3 years ago

OahMada commented 3 years ago

Yes, I promise I've read the Contributions Guidelines (please feel free to remove this line).


Please type "I already searched for this issue": I already searched for this issue Edition: (1st or 2nd) 1st Book Title: ES6 & Beyond Chapter: 7, Meta Programming Section Title: Well-Known Symbols Problem: In the Symbol.isConcatSpreadable part, you said "The @@isConcatSpreadable symbol can be defined as a boolean property on any object (like an array or other iterable) ," but I don't think any object/iterable can fit here, since concat is a method on Array or String prototype objects. I tried with a custom non-array one, it didn't work.

getify commented 3 years ago

Many details from 1st edition are no longer accurate. However, as the contribution guidelines spell out, I'm not accepting any updates to first edition books. Thanks.

OahMada commented 3 years ago

sorry

mohitpal2621 commented 4 months ago

It can be invoked like this:

const arrayLike = {
  [Symbol.isConcatSpreadable]: true,
  length: 2,
  0: 1,
  1: 2,
  2: 99, // ignored by concat() since length is 2
};
console.log(Array.prototype.concat.call(arrayLike, 3, 4)); // [1, 2, 3, 4]