loading...

re: 5 Uses for the Spread Operator VIEW POST

FULL DISCUSSION
 

Great summary! Two extra thoughts:

  • Another handy use is to convert iterable objects to Arrays when you need the Array methods:
  /* Filtering a Set */
  const fruit = new Set(['apple','banana','avocado','watermelon'])
  // No no no!
  fruit.filter(f => f.startsWith('a')) // TypeError: fruit.filter is not a function
  // Instead...
  [...fruit].filter(f => f.startsWith('a')) // ["apple", "avocado"]

  /* Mapping over a generator's output */
  // counts from low to high-1
  function* range(low, high) {
    for (let i=low; i<high; i++) {
      yield i
    }
  }
  // No no no!
  range(1,10).map(n => n**2) // TypeError: range(...).map is not a function
  // Instead...
  [...range(1,10)].map(n => n**2) // [1, 4, 9, 16, 25, 36, 49, 64, 81]
  • Just a thought I had: I sort of wish that your error example worked like Object.entries, and in fact that Objects were iterable as entries the way that Maps are. I wish I could do stuff like this (but to be clear, this does NOT currently work):
  const o = {'a': 10, 'b': 20}
  [...o] // [["a", 10], ["b", 20]]
  for (const entry of o) console.log(entry)
  // ["a", 10]
  // ["b", 20]

Sigh... but I dream...

Code of Conduct Report abuse