What is a for-of loop in JavaScript?

A for-of loop is like a for loop that specializes in iterating through iterable bodies. Iterating through iterable bodies is a very common programming practice, so, having a dedicated loop for it can be very useful.


Example

// Using the traditional for-loop
iterable = [11,22,33,44,55]
for(let i =0; i<iterable.length; i+=1)
{
console.log(iterable[i])
}

For-of vs. for-in

Another loop that does a very similar job is the for-in loop. However, it is very important that you do not confuse them.

// Using the for-in loop
iterable = [11,22,33,44,55]
for(let index in iterable) // The for-in loop
{
console.log(index) // prints the indices rather than elements
}
for-of loop
for-of loop
for-of loop
for-of loop

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved