DEV Community

Cover image for Explanation of JavaScript's for...in and for...of Loops
Faisal Nawaz
Faisal Nawaz

Posted on

Explanation of JavaScript's for...in and for...of Loops

Hey everyone,

I’m Faisal Nawaz, a frontend developer with over 10 years of experience. I’m honored to contribute to this article.

for...in Loop

The for...in loop iterates over the enumerable properties (keys/indexes) of an object or array.

Example:

const fruits = ['Mango', 'Apple', 'Banana', 'Orange'];

for (const item in fruits) {
console.log(item);
}

// Output: 0, 1, 2, 3

for...of Loop

The for...of loop extracts the actual values of iterable objects (like arrays).

for (const item of fruits) {
console.log(item);
}

// Output: Mango, Apple, Banana, Orange

Key Difference
for...in → Returns keys/indexes
for...of → Returns values

This distinction helps in choosing the right loop for different use cases in JavaScript.

This distinction helps in choosing the right loop for different use cases in JavaScript.

Top comments (0)