javascriptfor-loopiteratorprototype

Custom Iterator for Number Prototype in JS


Recently I learned about JS iterators, beeing used in a for( of ) loops. Since in JS even primitives have a prototype, I wondered if it is possible to extend the Number prototype so that the following would be a valid expression:

for(let i of 10) console.log(i); //0 1 2 3 4 5 6 7 8 9

Obviously this would only work for integers, but is there a way to implement this?

Hopefully there is, but I wasn't able to create this myself since I'm new to this part of JS...


Solution

  • Sure, just define Number.prototype[Symbol.iterator]:

    Number.prototype[Symbol.iterator] = function() {
      let currentNum = 0;
      return {
        next: () => (
          currentNum == this
          ? { done: true }
          : {
            value: currentNum++,
            done: false
          }
        )
      }
    }
    for (const i of 10) console.log(i);

    But mutating the built-in objects (like the global Number) is very bad practice - it would be better to find another way to do whatever you're trying to accomplish, if at all possible.