Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn for...of and forEach | Building Conditions and Repetition
Conditional Statements and Loops in JavaScript

bookfor...of and forEach

Imagine you have a grocery list and you want to check every single item to make sure nothing is missing. You would start at the top of the list and look at each item one by one until you reach the end. In programming, when you want to process every item in a listβ€”like an array of fruitsβ€”JavaScript gives you two handy tools: the for...of loop and the forEach method. Both help you visit each element in an array, but they work in slightly different ways.

12345
const fruits = ["apple", "banana", "cherry"]; for (const fruit of fruits) { console.log("I need to buy " + fruit); }
copy
12345
const fruits = ["apple", "banana", "cherry"]; fruits.forEach(function(fruit) { console.log("I need to buy " + fruit); });
copy
question mark

Which loop is generally the simplest choice when you want to process every item in an array, one after another, without skipping or changing the order?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 5

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Suggested prompts:

What is the difference between for...of and forEach in JavaScript?

When should I use for...of instead of forEach?

Can you explain how these loops work with other data types?

Awesome!

Completion rate improved to 7.69

bookfor...of and forEach

Swipe to show menu

Imagine you have a grocery list and you want to check every single item to make sure nothing is missing. You would start at the top of the list and look at each item one by one until you reach the end. In programming, when you want to process every item in a listβ€”like an array of fruitsβ€”JavaScript gives you two handy tools: the for...of loop and the forEach method. Both help you visit each element in an array, but they work in slightly different ways.

12345
const fruits = ["apple", "banana", "cherry"]; for (const fruit of fruits) { console.log("I need to buy " + fruit); }
copy
12345
const fruits = ["apple", "banana", "cherry"]; fruits.forEach(function(fruit) { console.log("I need to buy " + fruit); });
copy
question mark

Which loop is generally the simplest choice when you want to process every item in an array, one after another, without skipping or changing the order?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 5
some-alt