3.5 Array Iteration - Video Tutorials & Practice Problems
Video duration:
3m
Play a video:
<v ->We saw in the last chapter how to iterate through strings.</v> And while you might find yourself using string iteration from time to time, you'll end up using array iteration all the time. This is pretty much what arrays do in life is they get iterated through. So, we're going to look at the simplest way building on the for loop that we talked about in the last chapter. And as with the comments involving string iteration, this is not the best way to iterate through arrays, but it is the best way to get started for now, because it's the kind of iteration that we're in a position to do at this moment. Let's review string iteration as the first step. I have the soliloquy variable here. So recall in the last chapter that we did a for loop like this. We started a loop variable at zero. soliloquy.length. And then we incremented it, i++ just adds one each time to the loop. And then we printed out each character. Using charAt of i like this. But we saw previously in this chapter that strings actually do support the square bracket notation like this, so let's convert to that. So this is now the ith element of soliloquy. Same result. And so this suggests a wave iterating through an array. So here's a. You can just go from i=zero, a.length, i < a.length. i++ same thing. And then we can say the ith element of a. By the way in case you're wondering this iteration variable gets created on the fly and is local to this loop. So if we look at it here, it doesn't exist. That's why we were able to reuse it several times in a row without getting an error. Remember if I said let a equal something that gives me an error because I already defined a. But as far as JavaScript is concerned, as soon as you get out of this loop, i doesn't exist anymore. This for loop method for iterating is perfectly functional and indeed is the most common way of iterating in a large variety of languages. But as we'll see in chapter five there is a better way using what's called a for each loop.