Table of contents
for...in loop
Syntax
for (variableName in arrayName/objectName)
statement
The for-in loop will loop through the enumerable properties of a JavaScript iterable.
This means that when you iterate over an array the variableName in the syntax will return the index of the array. This is shown below:
const cities = ['Mumbai', 'Pune', 'Bengaluru']
for (const index in cities) {
console.log(index)
}
/* Output:
0
1
2
*/
In the case of an object, the for-in loop will iterate over and the variableName in the syntax will return the key of the object. This is shown below:
const cities = {1: 'Mumbai', 2: 'Pune', 3: 'Bengaluru'}
for (const key in cities) {
console.log(key)
}
/* Output:
1
2
3
*/
for...of loop
Syntax
for (value of array/string)
statement
As the syntax says this loop iterates over the values sourced from the iterable.
It means that when you iterate the for-of loop over the array the value in the syntax will return the values of the array sequentially.
const footballClubs = ['Mumbai City FC', 'Kerala Blasters FC', 'Bengaluru FC']
for (const value of footballClubs) {
console.log(value)
}
/* Output:
Mumbai City FC
Kerala Blasters FC
Bengaluru FC
*/
In the case of a string, it will iterate through the length of the string and return each alphabet/special character.
const str = "Tushar"
for (const letter of str) {
console.log(letter)
}
/* Output:
T
u
s
h
a
r
*/
Note: Pure objects are not iterable in JavaScript, the for-of loop will not work on an object such as our ‘cities ’ object in the example above. Using the ‘map’ method is a much better way to work with the values inside of a JavaScript object.
A tip to remember when to use for-in or for-of is really simple. If you need to work with an index then use for-in(dex) and when you need to work with value use for-of(value).