Trusted answers to developer questions

What is a for-of loop in JavaScript?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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

RELATED TAGS

javascript
for-of
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?