From the course: Learning the JavaScript Language
For loops: Sequential - JavaScript Tutorial
From the course: Learning the JavaScript Language
For loops: Sequential
- [Instructor] When we talk about programming computers it's always with the goal of making the machine do something that we're not so good at, or just don't want to do. One of the things that a computer can do really well is the same thing over and over again. What I'm talking about is called looping or iterating. In this lesson we're going to look at for loops. Specifically we're going to look at sequential for loops. This is a way of telling the machine to do something over and over again a certain number of times. To start off, we'll write a for loop that logs a console message 10 times. It looks like this. You write the word for, and then in some parentheses you'll put three statements. First, you initialize some sort of variable, which is usually referred to as the loops counter or index. It's very typical when you see for loops in the wild for the variable to be called i for index. It's just sort of a convention. But you can call it anything you want. For its value, you'll often see zero, very similar to what we've seen with arrays. This is a convention people use, starting with zero. It's not required, but because it's very common, maybe the most common, that's what we'll use here. So we'll start out with that initialization setting the variable i to zero, and then we'll add a semicolon. The next statement is a condition. This condition determines when we will stop looping. In this case, we want to loop 10 times, so I want to make sure that i is less than 10. We started with zero, so if we were to go through until our counter equals 10, that would actually be 11 times through the loop or 11 iterations. So we write this in as i is less than 10, and add another semicolon. So far we're just starting out with zero, and then checking that i is less than 10. So now we have those first two parts, but how do we get to the end? Every time through this loop, we're going to increment i. There are various ways we can increment a variable, as we have seen previously. We could do i plus equals one. One way you'll often see it in for loops is i plus plus as well. Either one works. We'll go with i plus equals one for now. And then in some curly braces, we'll put the things that we want to happen every time this loop runs. Now here in node, I don't have to enter editor mode to get onto a second line because node recognizes, I think based on the curly braces, that we're continuing to edit the same block, and so it just does this for me. Those dots are added automatically just to show that it's doing some indentation. When you're writing your own code in an editor, you won't use any dots like this. So in those curly braces we put the things that we want to happen every time the loop goes. In this case, we're just going to do something simple. Which is using the console.log method to write something to the console. In this case, we'll put the value i. So every time this loop runs, in the console we will get whatever the value of i is at the time that that particular step through the loop is executing. Then we'll just add our final curly brace and that's it. To recap, this for loop has three statements. We initialize the variable called i to zero and then we stop once i is no longer less than 10. And every time through the loop we increment i by one. Inside the braces each time we go through the loop, we're writing the value of i to the console. Now let's execute this. We'll just hit Return. There we go. So we can see i started out at zero and each line is written out to the console one by one. The next time i is incremented by one, and we go from one to two and so forth. Continues all the way down the line. When i is nine, that line is written out, i is incremented one more time. Its value becomes 10. So the loop stops and we never see 10 written to the console. And just so it's super clear, I don't have to use zero for initialization. I'll copy this and paste it in. I could change i so it starts at one. And then I need to let the loop go as long as i is less than or equal to 10 this time. But everything else can be the same here, log i to the console, add my closing curly brace. Then when I execute it, this time instead of going from zero to nine, I go from one to 10. But otherwise it executes the same number of times and works the same way. And of course you can have as much stuff inside these curly braces as you want. You can take all kinds of action inside loops. Let's take a look at an example loop that's a little more like a real world example. So I'm going to minimize my terminal and open the two files from this chapter. A very common use case for for loops is to loop over the contents of an array. So here we have an array of page names. Home, about us, and so forth. There are six items in the array. Now in the real world, we might come up with some clever way of populating this array with page titles instead of writing them out statically as I've done here. Putting data in like this by hand is called hard-coding. And on real projects it can be something to avoid. For now, it's better for us to see exactly what data we have in advance, so it's fine. We have this array of page names, and we're going to write a piece of code that will look through every item in the array, and tell us whether the one we're looking at matches the actual page title of the page we're on. To do this on a real webpage in a web browser, we would be accessing the document variable web browsers provide via something called the document object model or dom. Which is the interface a web browser provides JavaScript developers for interacting with what's on the page. This document object has a property called title, which is the contents of the title tag on that page. You can see it here in this little snippet. So here's what we're doing with this for loop. We're starting with this variable set to zero, because as you remember, the first index in any array is zero. And then we're looping until we hit the length of the array. We're going over each one in sequence so we increment by one each time. And then inside the for loop, you can see these matching curly braces, we have an if block. We check if the title, using document.title, is the same as the current page name, which we're retrieving from this array using the index or counter. And if the current title matches the one that we're looking at in the array, we're going to log a message that says, "We are here," with the name of that page. And if it doesn't match, we're going to say, "We are not here." And again include the page title. So the first time through this we'd expect to look at the page name where i equals zero, which would be Home. The second time through it would be About Us. And every single time through we're going to take the same action that's inside the loop. If the document title matches, it's going to write the message to the console saying, "We're here." And if not, it writes the other one. To actually try this out, we're going to need an actual page. We can do this here in GitHub Code Spaces by opening the file, which is called sandbox.html. And then using the Go Live function. That opens a little stub web server with this page loaded. It doesn't have much meaningful in it, just a little bit of text. But having loaded this, I can open up the developer tools. Here in Chrome, that's in the View Developer, Developer Tools path. And now I'm going to have the dom available in the JavaScript console. Here in the Elements Inspector, I can look up at the HTML tag for the head of the document. And here's the title. In JavaScript, this is what's represented by that document.title property we looked at before. So let's take this code from the transcript file. We'll copy this, bring it over to our console, paste it, and let it execute. So let's note that it does run through every single item in the array, and here are all the messages. We're not here: home, about us, or contact us. We are here: JavaScript playground. You can see the title up here. We saw it in the Elements Inspector as well. And then News and Blog. We're not at either of those places either. If I wanted to stop the loop from running after I successfully find the right one, I can add a break statement. So here's the we are here condition. If I added a break here, this would break the execution of this for loop. I'm going to copy this block one more time and we'll try it out. I can hit this button here to clear the console. That just clears what's displayed. It doesn't clear the previously set values. Now if I hit Return, I can see all the ones that we are not, up until we reach the one that's correct and then the loop stops. One more quick note about this code. As programmers, we very much like not to repeat ourselves. So you may look through this block of code as you're writing and say, "Ah, look at this. I have this little piece where I'm getting into that array by index, and I'm doing that three times." This is ripe for rewriting. So what we can do is every time through the loop we can set a variable which could be called current page title and set it to page names sub i. Then we can rewrite our comparisons so they use current page title instead. This is nice because not only are we not having to rewrite this somewhat obscure-looking construct several times, but because we've given this a variable with a descriptive name, it makes it very clear what we're doing when we use it in these subsequent lines. That just makes it a little easier to read what's going on. In a block of code this short, that's not really a big win, but it's something. And helping yourself out by using meaningful variable names instead of something like page names sub i, maybe just a little bit less meaningful can be a great help. Especially as your program builds in size over time. And that completes our first look at using sequential for loops to do the same thing over and over again.