Loop (for…of) vs (for…in) in JavaScript

Vahid Akhtar
2 min readOct 2, 2020

--

for..in and for…of loops give us a very clean and concise syntax to iterate over all kinds of iterables and enumerables like strings, arrays and object literals.

Both for..of and for..in statements iterate over lists; the values iterated on are different though, for..in returns a list of keys on the object being iterated, whereas for..of returns a list of values of the numeric properties of the object being iterated.

Let’s see some examples

Array of Objects

let arrOfObjects = [
{id:1,title:'Java'},
{id:2,title:'Python'},
{id:3,title: 'Nodejs'},
{id:4,title:'JavaScript'}
];

Array of Strings

let arrOfString = ['React', 'Angular', 'Vue', 'JavaScript'];

for…in loop for arrOfObjects and arrOfString

for(let name in arrOfString){
console.log(name); // 0 1 2 3
}
for(let obj in arrOfObjects){
console.log(obj); // 0 1 2 3
}

To get actual values we need to pass the index in for…in loop.

for(let name in arrOfString){
console.log(arrOfString[name]);
}
for(let obj in arrOfObjects){
console.log(arrOfObjects[obj]);
}

Output(for…in)-

for…in

for…of loop for arrOfObjects and arrOfString

for(let name of arrOfString){
console.log(name);
}
for(let obj of arrOfObjects){
console.log(obj);
}

output(for…of)-

for…of

Key differences

for…of is a new loop in ES6 that replaces both for...in and forEach() and supports the new iteration protocol.

Use it to loop over iterable objects (Arrays, strings, Maps, Sets, etc.)

const array = ['10', '20'];
for (const [index, element] of array.entries()) {
console.log(`${index}-${element}`); // 0-10 1-20
}

Looping over the [key, value] entries in a Map.

const map = new Map([
['React', 'Yes'],
['Vue', 'No'],
]);
for (const [key, value] of map) {
console.log(`${key} => ${value}`); // React => Yes Vue => No
}

That’s all for now! I hope the above simple practice will help.

Thanks

--

--

Vahid Akhtar
Vahid Akhtar

No responses yet