Since I'm trying to grasp the concept of iterables in JavaScript, I built one with the following code:
let range = {
  from: 0,
  to: 5
};
range[Symbol.iterator] = function() {
  return {
    current: this.from,
    last: this.to,
    next() {
      if (this.current <= this.last) {
        return { done: false, value: this.current++ };
      } else {
        return { done: true };
      }
    }
  };
};
for (let num of range) {
  console.log(num);
}
The Symbol.iterator method returns an object that contains one method (next) and two properties (current and from). The properties within this object are equal to the properties within the object range.
Since current equals this.from and last equals this.to, I assumed that I could use this.from and this.to directly from within the method next as so:
let range = {
  from: 0,
  to: 5
};
range[Symbol.iterator] = function() {
  return {
    next() {
      if (this.from <= this.to) {
        return { done: false, value: this.from++ };
      } else {
        return { done: true };
      }
    }
  };
};
for (let num of range) {
  console.log(num);
}
However, doing this prevented the iteration from starting. Having observed this, I have two questions:
- Why can the properties - currentand- lastuse the keyword- thisand have it refer to the object- rangewhereas the method- nextcannot?- current,- last, and- next()are all part of the same object, which is returned by- Symbol.iterator.
- Also, given that - Symbol.iterator()returns a separate object, shouldn't the- thiskeyword within that object refer to that object itself? In other words, shouldn't the properties- currentand- lastnot be able to access the properties from- rangeusing the keyword- this? Isn't- rangea separate object?
 
     
    