How to Use for of and for in Loops in JavaScript
The new for of
and for in
JavaScript utilities provide a clean and simple way to perform loops. But in what scenarios should you use one or the other?
In this guide, we are going to take a look at when we should use either a for in
or a for of
loop in JavaScript.
For of
for of
should be used to iterate through strings
, arrays
, maps
, sets
, generators
and DOM node collections
. Let's have a look an example of for of
in action and go through what the code is doing.
var ages = ['45','18','16','25','32','14'];
var under = [];
for (let age of ages) {
if (age <= 18) {
under.push(age);
}
}
console.log(under);
["18", "16", "14"]
In the above example, we are looping through the ages
array and checking if each age is of the value 18
or under. If true the item is pushed to the under
array.
The nice thing about for of
is it works just like a foreach
loop in PHP. You don't need any logic to count the length of the array to tell for
to only loop that many times.
Let's try another example. This time with a string.
var word = 'hello';
var chars = [];
for (let char of word) {
chars.push(char);
}
console.log(chars);
["h", "e", "l", "l", "o"]
for of
splits the string into its individual characters which are then looped through. In the above example, each char is getting pushed to the chars
array.
For in
for in
is used to loop through the properties of an object. It can also be used to get the index keys from arrays
and strings
. Let's loop through an object using for in
.
var item = {
name: 'a blog post',
content: 'some text',
url: 'slug'
};
for (let prop in item) {
item[prop] = item[prop].toUpperCase();
}
console.log(item);
{ name: "A BLOG POST", content: "SOME TEXT", url: "SLUG" }
In the above example we are looping through all the property names in the item
object and then changing the content in each to uppercase.
The same can be done with a string. In the example below we are looping through the word
string and pushing its index number to a new array.
var word = 'hello';
var keys = [];
for (let key in word) {
keys.push(key);
}
console.log(keys);
["0", "1", "2", "3", "4"]
Conclusion
You now know the difference between using in
and of
in a for
loop and how to apply them to your code.