Javascript Iterators

Hi

I am practicising JS and struggling to understand when we declare and initialize variable with 0 and then use it in if statement or for loops. Can any one explain what actually this counter variable is doing in the code? I mean what counter++ is doing in the if statement and how can we assign counter as Value in the return object.

Please post your actual code instead of a picture. Thanks

class Sequence {
    constructor( start = 0, end = Infinity, interval = 1 ) {
        this.start = start;
        this.end = end;
        this.interval = interval;
    }
    [Symbol.iterator]() {
        let counter = 0;
        let nextIndex = this.start;
        return  {
            next: () => {
                if ( nextIndex <= this.end ) {
                    let result = { value: nextIndex,  done: false }
                    nextIndex += this.interval;
                    counter++;
                    return result;
                }
                return { value: counter, done: true };
            },
            return: () => {
                console.log('cleaning up...');
                return { value: undefined, done: true };
            }
        }
    }
}

it is just being assigned as value of a property in an object literal, I am sure you have seen many times a value being added to an object literal

every time that if statement is executed, counter is increased by 1

1 Like

We use iterators to set the number of times a piece of code will repeat. Woven in loop we want to run 5 times for example, we can declare an iterator with startign value 0, add 1 everytime the code is repeated and quit the loop when the value reaches 5.
counter ++ is shorthand to say counter += 1, or counter = counter + 1
Keep in mind iterators can be very flexible. You might make an iterator that counts backwards, or increment its value with more than one, or conditionally increment it, as long as it fits the behavior you wish to achieve, or the iterator value is used for other purpose.

for (let iterator = 0; iterator < 5; iterator ++) {
  // run five times
}

for (let iterator = 1; iterator < 10; iterator += 2) {
  // print all odd numbers in the range 1 .. 10
  console.log(iterator)
}

const string = 'backwards'
const length = string.length
for (let i = length - 1; i >= 0; i --) {
  // spell "backwards" backwards(sdrawkcab)
  console.log(string[i])
}

let arr = [ 2, 16, 7, 26, 30, 75, 8]

for (let iterator = 0; iterator < arr.length; iterator ++) {
  console.log(arr[iterator])
  // if you encounter arr element equal 16, skip next element
  if (arr[iterator] === 16) {
    iterator ++
  }
}

Iterators are just a variable/value which, we use to “count” some effect. It has its value, which can be used for anything, just like any other variable.

1 Like

variable ‘nextIndex’ is taking ‘start’ value, giving ‘interval’ during iteration and run it till the value reaches to the ‘end’.
What counter is doing in this code? whats its purpose? We are taking it 0, incrementing it in if statement and returning it as value but not sure what actually this is doing in this code?

Well, its hard to tell, the code is just a snippet from a bigger picture and there are lot of stuff involved like class/object oriented logic and it also looks to be dealing with closure. Closure is when we store certain variable inside a function and provide access to that variable outside. We have counter, which is defined inside this [Symbol.iterator] method, but we also return that object, which contains a next method, which does some stuff with the counter and then returns a data object of its own, including that counter value. This whole class will be utilized somwhere and has some purpose in a certain bigger logic, but its no way telling(at least for me), what purpose it has, without context and only seing a small piece of it. You should look where in the that project the Sequence class is called, there would be an object created with it and on that object those methods would be called. I imagine that next method will be called in some loop or something

I don’t know all that much about iterators but if you manually call next() you can see the value.

function makeRangeIterator(start = 0, end = Infinity, step = 1) {
  let nextIndex = start;
  let iterationCount = 5;

  const rangeIterator = {
    next() {
      let result;
      if (nextIndex <= end) {
        result = { value: nextIndex, done: false };
        nextIndex += step;
        iterationCount++;
        return result;
      } else {
        console.log(`Iteration count: ${iterationCount}`); // Iteration count: 10
        return { value: iterationCount, done: true };
      }
    },
  };
  return rangeIterator;
}

const it = makeRangeIterator(1, 5, 1);

let result = it.next();
while (!result.done) {
  console.log(result.value); // 1, 2, 3, 4, 5
  result = it.next();
}

console.log(it.next().value); // 10

Don’t think you can see it when done is true with Symbol.iterator. I think it works the same as without the value and just an object with done: true.

class Sequence {
  constructor(start = 0, end = Infinity, interval = 1) {
    this.start = start;
    this.end = end;
    this.interval = interval;
  }
  [Symbol.iterator]() {
    let counter = 5;
    let nextIndex = this.start;
    return {
      next: () => {
        if (nextIndex <= this.end) {
          let result = { value: nextIndex, done: false };
          nextIndex += this.interval;
          counter++;
          return result;
        } else {
          console.log('counter', counter); // counter 10
          return { value: counter, done: true };
		  // Same as this I think
		  // return { done: true };
        }
      },
      return: () => {
        console.log('cleaning up...');
        return { value: undefined, done: true };
      },
    };
  }
}

const seq = new Sequence(1, 5, 1);
for (const val of seq) {
  console.log(val); // 1, 2, 3, 4, 5
}
1 Like

By the way, is there any reason you’re specifically practicing creating an iterator? I’ve never seen a case where I’ve needed to create a custom iterator for standard front end client work. I certainly benefit from the iterable property of built-in arrays and objects by being able to use spread syntax (...) etc., but I haven’t ever found a need to understand how that works under the hood.

To clarify what I mean, I think if your goal is to “learn iterables” or something like that, then in my personal experience, here’s all you need to know.

  1. There are some features that work with iterables (spread syntax, for…of loops)
  2. Objects, Arrays, and Strings (amongst others) are iterables
1 Like

Hi Colin, thanks for the suggestion, offcourse these are valuable when you get from someone experienced. This is the code i have seen on one of the learning websites and i am just trying to understand it thoroughly as i am beginer so i dont know what actually works in real world.

I am following this tutorial: The Essential Guide to JavaScript Iterator

and the code is in Iterator section

My personal opinion then is that there is very little benefit to you learning how to make iterables.

I would suggest you keep working on learning more fundamental concepts. Are you going through the freeCodeCamp JavaScript curriculum?

Yes i have cleared many concepts but the problems start when i read long code which is mix of many concepts and one of those concepts create confusion.
I am focusing on ES6 concepts and Iterables are mentioned in it

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.