5.4 Iteration for Each - Video Tutorials & Practice Problems
Video duration:
8m
Play a video:
Video transcript
<v Instructor>Now that we know how to define functions,</v> it's time, finally, to learn how to iterate what I consider to be the right way. So far we've iterated using a plain for loop. And to be fair, this is the way that looping has always been done in languages like C. But there's a more elegant way to do it that doesn't involve counting out each element in turn using an auxiliary counting variable like i, as we've seen before. So let's review that. Let's define a simple array choosing numbers more or less at random. So this is our array. Now, recall from before that the way we iterated through this was to use a counter variable that we called i. For let i starts at the zero with index zero, i less than the length of the array. And then we increment i. And just log it. Here we use the bracket notation. Now, probably the most common cases of iteration involve the element a of i, but not the counter variable itself. So for that common case, there's a way to iterate through the elements directly using a function called forEach. The equivalent to this for loop looks like this, a.forEach, and then the forEach method takes a function. Now, it's a special kind of function. It's a function that doesn't have a name, also called an anonymous function. All we need to do is type function and then the argument that represents the element of the array. We can call it anything. I'll call it element. And then as usual, we have a block of code. And in this case, let's just print it out as we did before. Now, you'll note that this is a closing curly brace, but we also need a closing parenthesis for the forEach method, like this. Now, when I read this, I typically don't read the word function. I just think to myself a.forEach element, then do something with that element. If we hit return, boom, it's exactly the same as before. All right, let's open up a file and redo a couple of our previous iterations using forEach just to reinforce this idea. I'll call the file foreach.js. And here it is. Let's do this. Before we had ant, bat, cat, and then number 42. And we can just do the same thing we did in the REBL, a.forEach function, and remember, I like to think that the word function isn't there. So a.forEach element. And now you can see here that the editor has actually made the closing parenthesis for me, so I'm gonna do a space open curly brace return, and that closing curly brace, closing parenthesis is there automatically for me. I'll just have to remember to put in a semicolon. Let's print it out. And let's run it using Node. There we go. Let's look at another example. Remember we had a soliloquy from Shakespeare's Hamlet. And we can iterate through each character. Now, before what we did was used a for loop and use the charAt method like this. Just wanna remind you of this. So it prints out all of the letters in the soliloquy like that. We can also do it like this. Remember that we can use the square bracket notation. It's the same there. But we've seen before that there's a way to convert a string into an array either by splitting on the empty string or using array.from. If we do that, then we have an array of characters, and we can forEach through them. So that looks like this. Array.from soliloquy.forEach function element. Open a curly brace. Get rid of this here. Get rid of this here. And instead of soliloquy of i, it's just element. And in fact, let's say character here to be more specific. And there we go. It's exactly the same. So I like this way of doing things better because it reads more like English. It feels more natural. Array from soliloquy for each character, console.log character. Iterating for i equals zero i less than some length i plus plus is a little more detailed, right? I don't really care about how long the collection or string or string array is. What I care about is printing out each character. So the forEach method lets us operate at a level of abstraction that to me feels a lot more natural. Pretty much every collection of elements in JavaScript can be iterated over using forEach. We've seen here arrays, but later on in this tutorial, we'll talk about the result of a powerful method called query selector all, which isn't technically an array, but it won't matter because we'll be able to use forEach to iterate through it element by element. And now here's a little bonus. I promised to tell you how to sort an array in a better way than defining a function just to do the comparison. So remember the comparison function had to be plus one when a was greater than b and negative one when a was less than b and zero when a was equal to b. But in fact, it doesn't have to be one or negative one. It can be positive or negative period. So if you do the math on that, we can actually get the sign right by calculating a minus b. So let the array equal eight, 17, 42, and 99 is what we had before. And then a.sort, remember, does it alphabetically. That's not what we want. So let's sort it using an anonymous function that returns a minus b. We can do it all in line like this. We don't need any new lines. And there we go. So this is the way to sort a numerical array without defining a function just to do the comparison. This is still a little cumbersome but it's a lot better than doing it the other way. And you can see why I couldn't tell you how to do it before. It does require this important idea of an anonymous function, a function we create on the fly, something that's so temporary we don't even have to give it a name.