I am currently participating in the #100DaysOfCode challenge, and on day 12 after I had posted what I learned for the day, Sebastian asked me on Twitter. "Can you explain the difference between 'for of' and 'for in'?" ๐จ๐จ
Prior to that day, I had scarcely gone through the for-in loop. So I gave an answer "The basic difference I noted is the for of loops over strings and arrays but not with objects while the for in is used to loop over objects." That was the most I knew on this topic however, Sebastian went on to explain the two loops and shared links to its examples on stack overflow. I was able to do a bit of study on the two loops and thought I should do an article on them. so here we go. ๐
For Of Loop
The for of statement was released with the sixth edition of the ES6 around 2015 and it allows the user to loop through iterable objects such as (arrays, strings, sets, maps e.t.c)
The syntax of the for of loop is:
- Element : These are the items in the iterable and they can be declared with either var, lets, or const.
- Iterables: These are the object properties that are iterated.
Looping through an array
In the example above the statement is used to iterate over the meals array and display all its values.
Looping through a string
The statement iterates through the string and logs its values to the console.
For In Loop
Unlike the for-of loop, the for-in loop has been available since the first edition of the ES6 and it allows the user to loop through the properties of a JavaScript iterable, I will explain with practical examples.
The Syntax of the for-in loop is
- A key/variable A different property name can be assigned to key on each iteration.
- Object Object whose non-Symbol enumerable properties are iterated over.
Looping through an array
The for in returns the index of the values in the array. However, if you don't want to return the index but the value itself, you can do this:
Looping through a string
Looping through an object
The code above shows how the for-in loop is used to iterate over objects and print it's properties.
- The object key is assigned to the variable key.
- menu[key] is used to access the value of the key.
Note: You should not use for...in to iterate over an array where the index order is important.
I found this on one of the links Sebastian shared with me on the difference between for in and for of Both for..in and for..of are looping constructs that are used to iterate over data structures. The only difference between them is the entities they iterate over:
for..in iterates over all enumerable property keys of an object
for..of iterates over the values of an iterable object. Examples of iterable objects are arrays, strings, and NodeLists.
I hope you enjoy reading this article ๐
`