for..of vs for..in loops in JavaScript
In this post we will give you information about for..of vs for..in loops in JavaScript. Hear we will give you detail about for..of vs for..in loops in JavaScriptAnd how to use it also give you demo for it if it is necessary.
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 meansthe 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 of keys best use case to use with iterable objects.
-
for..in loop best use case is to use with enumerable objects.
Hope this code and post will helped you for implement for..of vs for..in loops in JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs