by Sai gowtham

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

  1. for..of loop helps to get the values instead of keys best use case to use with iterable objects.
  2. for..in loop best use case is to use with enumerable objects.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course