StoryMarch 18, 20241 min read

“For in” VS “For of” Loop in Javascript

Today we are going to learn what are for in and for loop is, and find the deference between both of them.


“For in” VS “For of” Loop in Javascript

Photo by Kier in Sight Archives on Unsplash

Hello Everyone!

Today we are going to learn what are for in and for loop is, and find the deference between both of them.

Then let’s start

for…in loop

The `for…in` loop is used to iterate over the properties of an object.

It works by iterating over the enumerable properties of an object, including inherited ones.

It’s commonly used with objects to iterate over their keys or properties.

Example:

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

for (let key in person) {
  console.log(key + ': ' + person[key]);
}

Output:

name: John
age: 30
city: New York

for…of loop

The `for…of` loop is used to iterate over iterable objects like arrays, strings, maps, sets, etc.

It loops through the values of the iterable objects.

Example:

const fruits = ['apple', 'banana', 'orange'];

for (let fruit of fruits) {
  console.log(fruit);
}

Output:

apple
banana
orange

In summary:

  • `for…in` is used for iterating over object properties.
  • - `for…of` is used for iterating over iterable values like arrays.

If you have questions or suggestions please write comment below 😊

Thank you for reading 📖