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.
for…of Loop
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.
- In simple words, for…of works with strings and arrays but not with objects.
For instance:
1cosnt str = "Hello World";23for(element of str) {4 console.log(element);5}6// H e l l o " " W o r l d
for…in Loop
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.
- Enumerable flag for properties created via simple assignment or property initializer are by default true.
- Enumerable flag for properties created via Object.defineProperty are by default false.
For instance:
1const student = {2 registration: "123456",3 name: "Sandeep",4 age: 33,5}67for(key in student) {8 console.log(key, student[key]);9}10/*11registration "123465"1213name "Sandeep"1415age 3316*/
Now let’s add a new property (marks) to student object and set it’s enumerable flag to false. With enumerable flag set to false, marks key won’t appear in result of for…in loop.
1const student = {2 registration: "123456",3 name: "Sandeep",4 age: 33,5}67Objec.defineProperty(student, "marks", {8 value: 98,9 enumerable: false,10})1112console.log(student.marks);13// 981415for(key in student) {16 console.log(key, student[key]);17}18/*19registration "123465"2021name "Sandeep"2223age 3324*/2526// marks key does not show up in the for...in loop result.
for…in also works with strings and arrays, because enumerable flag for string and array properties are also by default true.
- In simple words use for…in to loop over objects. Although for…in works with strings and arrays, but it is not suggested to use that way.
Conclusion
- for…of - Use to loop over strings and arrays.
- for…in - Use to loop over objects.
That’s it for this post, Thanks for reading, if you found this post helpful please do share and subscribe to my newsletter below or here.
Thank You!