This course has been updated! We now recommend you take the TypeScript Fundamentals, v3 course.

Transcript from the "Introducing Iterators" Lesson

[00:00:00]

>> Mike North: There are some abstract constructs we're gonna talk about. This is gonna look like we're doing things in a way that's harder than some obviously simpler paths. But I'm taking you somewhere that's worth going to. So follow along with me. So iterators, and the point of an iterator is it allows us to kind of walk through a linear data structure of sorts, right?

[00:00:26] A sequence of values. We can access one at a time from a collection. And you can think of the iterator as something that has a little bit of state in it. It keeps track of our current position. And this is similar to how a four loop would work, and you can see here we're actually using one in a four loop.

[00:00:47] But when we talk about an iterator, it is simply an object that has a function on it, and that function is called next, and the value of this function returns has two properties on it. One is value and the other is done. So you can see in this case, we have, this is a Fibonacci based iterator where we return an object from this function.

[00:01:18] And when we call next on the object returned from this function, we're going to compute the next Fibonacci value in the sequence and we will stop when we hit that termination condition, right, as soon as we go past ten we will stop. At that point we know we're done, but otherwise we are returning a little object that says, we are not done yet and here's your current value.

[00:01:43] So this is what that would look like. And you get the Fibonacci sequence where each number is the sum of the two previous numbers.