for..of vs for..in loops in JavaScript
In this tutorial, we are going to learn about for..of vs for..in loops in JavaScript with the help of examples.
In JavaScript, for loops are used to iterate over the arrays and helps to run some code inside the block until the given condition fails.
for..of Loop
for..of
loop is used to iterate over iterable objects it means
the objects which are iterable.
example: arrays.
const arr = [1,2,3,4,5,6];
for(let num of arr){ console.log(num);
}
//output - 1,2,3,4,5,6
In the above example, on each iteration, we are accessing the different number inside the array by using for of
loop.
for..in Loop
for..in
loop iterates over the enumerable objects.
example: objects
const obj = {
a:1,
b:2,
c:3
}
for(let key in obj){ console.log(key);
}
//output
//first iteration: a
//second iteration : b
//third iteration : c
In the above example, by using for..in
loop we are accessing the object keys but not values.
Let’s see how to access the object values instead of keys.
const obj = {
a:1,
b:2,
c:3
}
for(let key in obj){
console.log(obj[key]);}
//output
//first iteration: 1
//second iteration : 2
//third iteration : 3
Conclusion
-
for..of loop helps to get the
values
instead ofkeys
best use case to use with iterable objects. -
for..in loop best use case is to use with enumerable objects.