Lesson Description

The "For Loops" Lesson is part of the full, Getting Started with JavaScript, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Kyle explains the concept of for loops in JavaScript, detailing the syntax and components of a for loop, including the variable, condition, and update sections. He demonstrates how to loop through arrays using for loops and discusses nesting for loops, early exit with break, and skipping iterations with continue. Kyle also introduces alternatives like for of loops for arrays and for in loops for objects, highlighting common mistakes such as infinite loops and off by one errors. Finally, he provides an exercise to create an array of even numbers and calculate their sum using separate for loops.

Preview

Transcript from the "For Loops" Lesson

[00:00:00]
>> WebDevSimplified: And the next thing we're going to be talking about are for loops. So we've talked a lot about how we can run certain code based on conditions. Now we want to talk about how we can run the same piece of code multiple different times in a row. So a for loop, the basic syntax for it is going to be as follows. First, we use the word for that defines that we want to create a for loop, and then we create some parentheses we're going to find all the different parts of what our for loop are going to contain.

[00:00:21]
After those parentheses, we put some curly brackets, and inside here is all the code we want to run every time our loop iterates. Now inside the parentheses for a loop, we have three different things that we need to define. First of all, we need to define the variable we're going to be looping over. Usually this is using a let variable because it's going to be updating itself. Oftentimes you'll see it called i, which stands for iteration.

[00:00:42]
So we'll set that to 0 to default our array at 0. We then put a semicolon followed by the next step, which is going to be the thing that checks to see if we need to exit our loop or not. So in our case, we're just going to say i is less than 5. So every single time that this evaluates to true, we're going to rerun our loop and we wait until this evaluates false. As soon as this evaluates false, we exit out of our loop.

[00:01:04]
We then put another semicolon followed by how we update our particular variable. Oftentimes you'll see it written like this i++. What that does is it just adds one to our i variable. It's the same as i equals i plus 1. Both of those are the exact same piece of code. This is just a more concise way of writing that exact same thing. So we've essentially created an array or not an array, a for loop that's going to loop through a certain number of times, starting with a value i of 0.

[00:01:29]
It's going to check every single time to see if our value has gone above 5, and every single time we add 1 to that particular value. So in here I'm just going to log out that i variable and we can look at the right hand side of our screen. It logs out 0, 1, 2, 3, and 4. So it runs this loop five different times. And the way that you can think about this top section of the for loop when you define it, because this is very confusing, is the very first thing that you write inside of here runs one single time before your loop starts.

[00:01:56]
You can almost think about this code as being written directly above where your for loop is. It essentially gets placed directly above your for loop. You then have this simple i less than 5. This second section is something that gets checked every single time before you run your loop, and if it returns true, the loop runs just fine. If it returns false, you run your code onwards after the loop is finished, so we can say here like console.log end.

[00:02:20]
And this is going to get run because as soon as this is no longer true, we just continue on with our program. This final section after the semicolon, you can almost think of this as being put at the very end of your for loop because this gets ran after all the rest of the code in your for loop runs, and this is what allows you to update that variable that you're checking against. So almost always in a for loop, the syntax is going to look like this.

[00:02:41]
You create a variable to start your loop. You create something that allows you to check that variable to see when you want to stop your loop. And then you create a way to update that variable with a new value to make sure you're keeping track of how many times you're inside that loop. And this is a very common syntax for looping through something a certain number of times. Now I have a few different kind of patterns here we looked at.

[00:03:02]
First of all, this is a normal pattern. We start at a low number, we end at a high number, and we're counting upward, but you could also count down if you wanted. You could start your i variable at 10. You can make sure that the i variable is always greater than or equal to 1, and instead of adding 1, we can use i--, which is the same thing as i equals i minus 1. So we just remove one from i every time.

[00:03:22]
We can even skip numbers. For example, using plus equals allows us to add 2 to i every time. It's the same as i equals i plus 2, so this allows us to skip every other number now instead of running every single iteration. Lots of different ways you can do it, but by far the most common is going to be a simple for loop like this that starts at a number, ends at a higher number, and increments by 1 every single time.

[00:03:42]
Now probably the most common place you're going to be iterating through things is when you have arrays, because arrays represent lists of data and you want to loop through those lists of data. So here I have an array of fruits apple, banana, orange, and grape, and I want to print out the values for those arrays. So we'll just copy this code so we can take a look at what it looks like running it live, and you can see, let's get rid of this output section right here, expand our screen a little bit.

[00:04:06]
There we go. You can see we have let i equals 0, so we're starting at 0. And for our check, we're just taking the length of our array because we know we can get the length of our array, which in our case is 4. So while i is less than 4, we continually loop through this and add 1 each time. So you can see the first index 0 is apple, index 1 is banana, 2 is orange, and 3 is grape. So when you want to loop through an array, very common syntax you'll see, you start i at 0, you make i less than the length of the array, and then you add 1 to i every single time.

[00:04:34]
And this is a very common syntax for looping through any array inside of JavaScript. You can also nest your for loops inside of each other. This works just like you would expect. Essentially it runs your first for loop one time and then it runs this for loop all the way until it finishes. So it'll run this for loop three different times, and then it runs the next iteration, this for loop, finally culminating with running this one three more times, and so on.

[00:04:58]
So you can see our output here. This first number stays as 1 for three iterations in a row because we run the middle part three times, essentially finishing this entire for loop. Then we change that number to 2, rerunning this loop three different times, and then finally it updates to 3, running this loop three different times. So nesting for loops works just the same as nesting anything else in JavaScript, as long as you understand how one for loop works, nesting them just means you now have multiple for loops to work with.

[00:05:25]
We also have the ability to change how our for loops work by exiting out of them early. For example, that break keyword which we kind of saw with switch statements, works with for loops as well. Anytime we use break inside of a for loop, it immediately exits from that for loop. So in this particular piece of code we have numbers 1, 3, 7, 2, 9, and 4, and we're looping through our array using that standard looping syntax we've talked about.

[00:05:48]
And I have a simple if check of if my numbers of i, which is whatever my current number is in my array, if it's greater than 5, I just want to log that out and then immediately exit the loop. So the first time I run this, 1 is not greater than 5, so we continue. 3 is not greater than 5, so we continue. And finally, 7 is greater than 5, so we get into this code right here which says found the 7 at index 2, and calling break immediately exits our loop.

[00:06:11]
It stops executing all the rest of our code and goes down to the very bottom of these curly brackets. Similar to how a switch statement with a break exits the entire thing. It's the same with a for statement or a for loop. Continue is a little bit interesting because instead of actually skipping you out of the entire for loop, it just skips the current iteration. Here we're just printing the numbers 1 through 5, but I want to skip the number 3.

[00:06:35]
So I check to see if my number is set to 3, then I call continue and continue essentially just stops executing the rest of my code so it skips everything that comes after it and moves me on to the next number. So it would add 1 to i and move me on to the number 4 and then start me back over at the very top of my loop. So you can see the output for this would just be 1, 2, 4, 5, because we're completely skipping what happens when we get to the number 3.

[00:06:57]
Now there are some for loop alternatives. For example, we can use a for of loop, which is a kind of a more condensed way to loop through an array inside of JavaScript. So for this one you can see here that we want to create a variable called fruit which comes from our fruits array. So this top array for looping is just our standard loop for an array, and the second one is that for of syntax. So you use the for keyword followed by your parentheses, but instead of defining your start, your end, and your check, you instead just define a variable which is whatever you're looping through is going to be.

[00:07:25]
So this is like each individual fruit in my array will be set to this fruit variable every time I loop through. You then put the of keyword, and after that you put the array you want to loop through. These two sets of code are going to do the exact same thing. Essentially this for of loop just allows you to create a more condensed way that says, I want to loop through this fruits array, and every single time I want to set the new value equal to this fruit variable right here.

[00:07:49]
A for in loop does the exact same thing, but it works for an object instead of an array. So here I can say const key in person. So the same exact thing instead of the of keyword we're using the in keyword, and instead of an array we pass in an object, and this will give me the keys of my object. So it'll give me name, it'll give me age, and it'll give me city. It won't give me the values. It'll just give me the string name, the string age, and the string city, which I can then use dynamically to access the different properties from my person like this.

[00:08:14]
So that allows me to loop through the different properties inside my object. This isn't really something I find useful that often, but it's important to know it's there in case you see it out in the wild. Now some really common mistakes, probably the most common, is you accidentally create an infinite loop. Here I start at the value 0. I'm making sure my value is less than 10, and I forgot to add one instead I'm subtracting one.

[00:08:34]
This will cause an infinite loop, which means that you need to completely shut down your browser and restart your browser to make sure that infinite loop stops running, otherwise it'll literally just run forever. So that's an important thing when you're working with loops. If all of a sudden your program seems to stop responding to you, that means you probably created an infinite loop. Another common error is an off by one error.

[00:08:54]
Essentially, that means that you accidentally ended your loop too early or you accidentally ran it one too many times. So here I'm doing my check where i is equal to 0 and i is less than my array length, but I'm accidentally putting a minus 1 at the end here, and that actually means I'm stopping my loop too early. So it's only printing out the first two values of my array. So when you're doing these different checks, make sure that you are actually looping through every value you expect to.

[00:09:17]
Same thing here, this should be less than instead of less than or equal to. So now I'm actually looping through one more value than I have in my array, so it's printing out 10, 20, 30, and undefined because it's trying to access a value that's not actually in my array. Again, just make sure you don't accidentally have that problem. Now I do want to move on to an exercise for this one. We're just going to write a for loop that creates an array of the first 10 even numbers.

[00:09:39]
So don't hard code this array. Instead, create a loop that creates this array brand new for you. Then I want you to calculate the sum of those numbers using a second for loop. So we should have two separate for loops. The first one creates you a brand new array with the numbers, the first 10 even numbers, and the second one adds those 10 even numbers together to give you a brand new total, and then just print out both of those different values.

[00:10:05]
So hopefully you had some time to go through that exercise. We'll take a quick look at the solution here. You can see here that first, like I said, we want to create our array by not hard coding it. So we're creating a for loop that loops through the first 10 numbers, and we're just multiplying them by 2 to give us the first 10 even numbers inside of this. There's multiple different ways you could do this.

[00:10:24]
For example, you could add 2 to your i variable every time and loop up to 20. It's really entirely personal preference. Both will work just fine. Then when we come down to calculate our sum, this one's going to be looping through that array, and again, you could use that for of way of looping or you can use a common for loop like this starting at 0, looping all the way up to the length of our array, adding 1 each time, and we're just accessing whatever the value of our number is, adding that into our sum variable.

[00:00:00]
So when we get to the bottom, we can log out our even numbers 2, 4, 6, 8, 10 all the way up to 20, and then log out the sum of those which is going to add up to 110.

Learn Straight from the Experts Who Shape the Modern Web

  • 250+
    In-depth Courses
  • Industry Leading Experts
  • 24
    Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now