How for loops work in JavaScript

There are 3 most common ways of using a for loop in JavaScript. This video demonstrates how for, for..in, and for..of loops works.

Code

// A simple `For` loop
for (var i = 0; i < 10; i++) {
console.log(i);
}
// The `for` loop with `var` creates variable in `global scope`
for (var i = 0; i < 10; i++) {
console.log(i);
}
console.log(i); // 10
// The `for` loop with `let` create the variable in `block scope`.
for (let i = 0; i < 10; i++) {
console.log(i);
}
console.log(i); // ReferenceError
// The `for` loop with var jumping over 2 numbers
for (let i = 0; i <= 10; i = i + 2) {
console.log(i);
}
// The variable in `for` loop initialization **cannot** be a `const`, as you are updating a variable
for (const i = 0; i <= 10; i = i + 2) {
console.log(i);
}
// The `for .. in` loop
// Get all the peoperties in the object
let weekDays = {
'Sunday': 0,
'Monday': 1,
'Tuesday': 2,
'Wednesday': 3,
'Thursday': 4,
'Friday': 5,
'Saturday': 6,
}
for (let property in weekDays) {
console.log(property)
}
// Get all the `enumerable` properties and values associated to the properties in the object
let weekDays = {
'Sunday': 0,
'Monday': 1,
'Tuesday': 2,
'Wednesday': 3,
'Thursday': 4,
'Friday': 5,
'Saturday': 6,
}
for (let property in weekDays) {
console.log(property, '=>', weekDays[property])
}
// The `for .. in` loop does not iterate on `non-enumerable` properties
let weekDays = {
'Sunday': 0,
'Monday': 1,
'Tuesday': 2,
'Wednesday': 3,
'Thursday': 4,
'Friday': 5,
'Saturday': 6,
}
Object.defineProperty(weekDays, 'SomeOtherDay', {
value: -1,
enumerable: false,
})
for (let property in weekDays) {
console.log(property, '=>', weekDays[property]) // SomeOtherDay will not be printed
}
// The `for .. of` loop
// Iterate over a `String`
let company = 'bonsaiilabs';
for (let character of company) {
console.log(character)
}
// Iterate over an `Array`
let tweetWords = ["bonsaiilabs", "content", "is", "fantastic!"];
for (let words of tweetWords) {
console.log(words)
}
// Iterate over a `Map`
let foodTastes = new Map();
foodTastes.set('cake', 'sweet')
foodTastes.set('pizza', 'salty')
foodTastes.set('vinegar', 'sour')
for (let foodTaste of foodTastes) {
console.log(foodTaste[0], foodTaste[1])
}
// Using `Destructuring assignment`
let foodTastes = new Map();
foodTastes.set('cake', 'sweet')
foodTastes.set('pizza', 'salty')
foodTastes.set('vinegar', 'sour')
for (let [food, taste] of foodTastes) {
console.log(food, taste)
}
// Iterate over an `Set`
let userIds = new Set(["bonsaiilabs", "meTheLearer", "internetBrowser"])
for (userId of userIds) {
console.log(userId)
}

Full Transcript

0:00 Hey there, it's Harit from bonsaiilabs. Welcome to the series on JavaScript. Today in this video, we are going to learn three most common ways of using for loops in JavaScript. So let's dive in. There are three common ways of writing. for loops using for, for N and for of let's look at each one of them one by one. The for statement creates a loop that consists of three optional expressions and closed in parenthesis and separated by semi-colons. And it is followed by statement. It starts with the initialization, It is followed by the condition and the final expression. Within the body of the for loops, we execute one or more statements. So let's start with an example. Let's say we create a variable called i with the initial value of zero, before any code could be executed in the loop, a condition is checked. So in our example, we check that the value of i should be less than 10 and after every loop execution, the final expression is evaluated. So we increment the value of i after every loop. Right now in the statements, we are printing the current value of i in the loop. Let's see that in action. So let's create our for loop now.

1:19 So as you see, we have created a for loop with the variables identifier called i. We check in the condition that the value of I should be less than 10 we're incrementing the value of I by one after every loop and in the body we are printing out the current value of i. Let's go ahead and run that. So as you see, when we run the for loop, we get the values from zero to nine. It did not print out the value of 10 why? Because our condition said that the value of I should be less than 10. When we initialize the identifier I we use the keyword called var. The challenge with var is when you initialize a variable using a var keyword, the variable identifier is created in the global scope. Let me tell you what I mean. So as you see, I'm trying to print the value of I after the for loop has executed and when we run it

2:14 [inaudible]

2:14 you see a value of 10 which means even though we wanted the value of i to be used only inside the for loop, the variable was created in the global scope and that's the reason we were able to get the value of i even outside of the for loop. Now this may not be desirable, so what should you do? So instead of using a var keyword to initialize the variables, you should use let keyword. So let initializes the variables in the block scope, which means once the for loop completes execution, the variable I will no longer be accessible. Let me show you what I mean.

2:49 So when I run the example, it printed out all the values from zero to nine but when we try to print the value of I outside of for loop, the variable I did not exist. So it is better and safer to introduce your new variables using the let keyword. Now the other type of for loop is a for-in loop. A for-in statement iterates over all enumerable properties of an object consists of two parts followed by the statements. It starts with the object over which you want to iterate. It assigns every property of an object to a variable and it is separated by the in keyword. And within the body you can have one or more statements. So let's say we have a weekdays object which consists of seven properties with the associated numeric values. So we want to iterate over the weekdays object and for every object we want to assign it a property called property. Now this property, when the loop starts would contain only the property keys and not the values. And within the body we are printing out what the property key is. Let's see that in action. So we have a weekdays object here with seven properties. Now we will use for in loop to iterate over the properties

4:06 [inaudible].

4:06 So as you see it iterating over week days and within every loop we are getting the property inside the P variable and we are printing that variable on the console. Let's run it. So when you run, you see all the properties printed on the console and not their associated values. The for in loop, iterates only over the property keys of an object. It does not iterate over the values. The third kind of for-loop is a form of loop. A for of loop iterates over iterables. Iterables are nothing but the objects that can be iterated upon such as arrays, string, map, set. And for every part of the loop, the variable gets the value from these iterables. And within the body of the for statement, you can have one or more statements doing something with these values. So for example, we can have a myIterable object, which has iterable properties and for every Iterable, we take the values and we put that in a variable called value. And within the statements we are printing out the value on the console. Let's see that in action. So string is iterable in JavaScript. So we have created a variable called Iterable and assigned it the value of the string called bonsaiilabs. So let's iterate over the Iterable using the for of loop.

5:19 So,

5:27 as you see, we are using a for of loop and we are iterating over the Iterable object. For every loop, we are putting the value inside the variable called V and all we are doing is printing out the value on the console. Let's run it. So as you see at the output, since the string is an Iterable, the for of loop picked every character of the string and printed that out on the console. Now we know that even the arrays are iterable. So how about we iterate over the arrays using the for of loop. So I've change the value of Iterable from string to an array. And it contains four elements as we see here. We're using the same form of loop to iterate over the array now. So let's run it and see the output. So as you see at this point in time, the for of loop iterated over every element of the array and every element became one element when printed on the console. We know that even set is an iterable. So can we iterate over the set using a for of loop? Let's try that. So I've changed the code so that our Iterable is no longer an array but a set and it contains three elements inside the set, and we're using the same form of loop to print the values inside the set on the console. Let's run them.

6:48 [inaudible]

6:49 So as you see, as expected, the for of loop printed every element of the set on the console one by one. So the question is, what's the difference between for of and for in? So the far of iterates over all the values of your iterables and for in only, iterates over the keys of the properties and not on the values. So when you have a use case of iterating over the Iterable, ask yourself whether you are only interested in the keys or the properties or you're interested in all the values and that will help you decide whether for in or for of is a good choice. And that's it. If you do like the video, please hit the subscribe button and stay tuned for more awesome content. Thank you.