العودة إلى الدورة

Array Iteration Methods: The forEach() Method

JavaScript: الدورة الكاملة للمبتدئين من 'الصفر إلى الاحتراف'

58. Array Iteration: The .forEach() Method

.forEach() is a high-order array method. It executes a provided function once for each array element.

Syntax

javascript array.forEach(function(currentValue, index, array) { // do something with currentValue });

Example: Logging Users

javascript const users = ['Anya', 'Ben', 'Chloe'];

users.forEach(function(name, index) { // The function passed to forEach is called a 'callback function' console.log(${index + 1}. ${name}); });

// We will use modern arrow function syntax (covered later) for brevity: users.forEach(user => console.log(user.toUpperCase()));

Key Limitation of .forEach()

  1. No Return Value: forEach() always returns undefined. It is only used for side effects (like logging to the console, or updating the DOM).
  2. Cannot break: You cannot use break or continue inside a forEach loop; you must complete all iterations.