We all know about the loop. A loop is a fundamental concept in any programming language. Generally, we use a loop for repetitive tasks or go through iterable objects. Remember everything in JavaScript is an Object.
Let’s see a traditional for loop in JavaScript. We will print all array elements using the following loop.
let continents = ['Asia', 'Africa', 'North America', 'South America', 'Antarctica', 'Europe', 'Oceania'] for (let i = 0; i < continents.length; i++) { console.log(continents[i]) }
Intro
Now, we will see the ‘for…in’ and ‘for…of’ loop. These are introduced in ES6, the sixth edition of EcmaScript. These loops are more straightforward for iterating through an iterable than a traditional loop. The syntax is so simple. Let’s see a pseudo example.
for (variable in/of iterable) { print variable }
for…in
To get all the index/key of an iterable object, it’s pretty handy. Let’s see an example.
let continents = ['Asia', 'Africa', 'North America', 'South America', 'Antarctica', 'Europe', 'Oceania'] for (let index in continents) { console.log(index) } // We can use these indexes to print the array elements. for (let index in continents) { console.log(`The value of index ${index} is: ${continents[index]}`) }
for…of
This one is the opposite of the previous one. To get all elements/values of an iterable object, it’s a good way. Let’s see an example.
let continents = ['Asia', 'Africa', 'North America', 'South America', 'Antarctica', 'Europe', 'Oceania'] for (let val of continents) { console.log(val) }
Not in the array, we can use these loops in other iterable objects. Let’s see.
let user = { name: 'Jhon Doe', email: 'jhondoe@example.com', age: 99, city: 'Boston, Massachusetts', country: 'United States' } for (let key in user) { console.log(key) }
Last Words
This blog is not an in-depth overview of these two loops. I try to make it simple and easy. I hope you got the purpose of these two loops.