An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
You don't know spread operator !
I was recently reading a blog post about iteration from Axel Rauschmayer (I suggest you follow him, all his posts are minegold for JS devs).
This post was mindblowing to me as I learned so much about iteratables in JavaScript.
Let's challenge our knowledge
Let me sum up a bit of what I learned here with a small challenge to you :
When I use the spread operator on a Number, I want the result to be an array that counts from 1 to the given value :
First steps to an answer
First thing to do is try the code for yourself and you will see that using a spread operator on a Number throws an error => Uncaught TypeError: X is not iterable
Then what is an iterable ?
An iterable is an object that defines an iteration behavior, meaning it has a property with a Symbol.iterator key and an iterator as value.
This iterator should respect the iteration protocol which means it is a function that returns an object with a next fonction that returns an object with 2 properties : "value" (the current iteration's value) and "done" (a boolean indicating weither we are done iterating with this iterator or not).
The spread operator is simply a consummer of such iterables: when you give it an iterable, it'll call the next function of its Symbol.iterator property until it returns an object with {done: true} (and push each time the result in an array).
Verify that with an Array
An array in JavaScript is an iterable since it has an iterator as a value of its property with Symbol.iterator key.
Here is how you can use this iterator :
Answer to the challenge
So how do I make the spread operator not throwing an error when given a number ? You set the Symbol.iterator property on the Number primitive wrapper object.
Let's make all numbers iterables !
Conclusion
Obviously you never want to change the prototype of a primitive wrapper object, it's too dangerous.
But the knowledge of how iteration and the spread operator works is I think very valuable as a developper.
Original Link: https://dev.to/parsyvalentin/you-don-t-know-spread-operator-3gk2
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To