
Hello Everyone,
The difference between for-of and for-in loop really troubled me when I was learning JavaScript. And with this blog, I will try to clear the confusion once and for all.
Let's understand them one by one.
The for...of statement creates a loop iterating over iterable objects, including built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.
I know that's not the explanation you came here for, So let me explain.
for...of loop works only with iterable objects. In JavaScript, iterables are objects which can be looped over.
String, Array, TypedArray, Map, and Set are all built-in iterables, because each of their prototype objects implements an @@iterator method. So, for...of loop works on the mentioned object types.
Object in JavaScript is not iterable by default. So, for...of loop does not work on objects.
For instance:
cosnt str = "Hello World";
for(element of str) {
console.log(element);
}
// H e l l o " " W o r l d
The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.
Explanation:
So, for...of does not work with objects (non iterables), Then how do we loop over keys and values of an object? And the answer is for...in loop.
for...in works with those properties whose enumerable flag is set to true.
For instance:
const student = {
registration: "123456",
name: "Sandeep",
age: 33,
}
for(key in student) {
console.log(key, student[key]);
}
/*
registration "123465"
name "Sandeep"
age 33
*/
Now let's add a new property (marks) to the student object and set its enumerable flag to false. With enumerable flag set to false, marks key won't appear in the result of for...in loop.
const student = {
registration: "123456",
name: "Sandeep",
age: 33,
}
Objec.defineProperty(student, "marks", {
value: 98,
enumerable: false,
})
console.log(student.marks);
// 98
for(key in student) {
console.log(key, student[key]);
}
/*
registration "123465"
name "Sandeep"
age 33
*/
// marks key does not show up in the for...in loop result.
for...in also works with strings and arrays, because enumerable flags for string and array properties are also by default true.
That's it for this post.
I am starting a Newsletter where I will share epic weekly content to build your skillset. If you are interested please subscribe to 8020 NewsLetter.
Thank You!