📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The forEach() method executes a provided function once for each array element.
Syntax
arr.forEach(function callback(currentValue [, index [, array]]) { //your iterator }[, thisArg]);
- callback - Function to execute on each element, taking three arguments:
- currentValue - The current element being processed in the array.
- index (Optional) - The index of the current element being processed in the array.
- array (Optional) - The array forEach() was called upon.
- thisArg (Optional) - Value to use as this when executing the callback.
Examples
Example 1: Simple Array.forEach() Example
var progLangs = ['Java', 'C', 'C++', 'PHP', 'Python']; progLangs.forEach(element => { console.log(element); });
Output:
Java C C++ PHP Python
Example 2: Converting a for loop to forEach
const items = ['item1', 'item2', 'item3']; const copy = []; // before for (let i=0; i<items.length; i++) { copy.push(items[i]); } // after items.forEach(function(item){ copy.push(item); });
Comments
Post a Comment
Leave Comment