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.
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.
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
}
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.
There are some features that work with iterables (spread syntax, forâŚof loops)
Objects, Arrays, and Strings (amongst others) are iterables
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.
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