Difference Between 'for...in' and 'for...of' Loop s
Samantha Diaz
Posted on July 8, 2022
This blog summarizes when to use 'for...in' and 'for...of' loops in JavaScript.
Difference
The 'for...in' loop is used for objects. The 'for...of' loop is used on data structures like arrays and strings.
It is possible to use a for in loop with arrays and strings. However, per JavaScript's MDN, the for of loop is preferred for strings and arrays as it returns the index as a number, whereas the for in loop will return the index as a string.
How to remember?
Think about for in loops as being inside an object. Since objects have no order, every item is associated inside it, all together. It's like a purse containing all your items - no order, everything is just inside.
Since arrays and strings have order, think about for of loops as in every item of an array or string. If you were reading a book (array) with chapters (indexes), you would say you're currently "reading chapter 3 of 30 in the book". So, think of it as 'for X index OF an array'.
For...in
For...in loops iterate through an object.
From the MDN Web Doc:
for (const variable in object) {
statement
}
Examples
const object = { a: 1, b: 2, c: 3 };
for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
// "a: 1"
// "b: 2"
// "c: 3"
const obj = { a: 1, b: 2, c: 3 };
for (var i in obj) {
console.log(i);
}
// "a"
// "b"
// "c"
For...of
For...of loops iterate over an array or string.
From the MDN Web Doc:
for (variable of iterable) {
statement
}
Examples
const array1 = ['a', 'b', 'c'];
for (const element of array1) {
console.log(element);
}
// "a"
// "b"
// "c"
const string = 'boo';
for (const value of string) {
console.log(value);
}
// "b"
// "o"
// "o"
Posted on July 8, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024