JavaScript forEach() Loop Exercises
JavaScript forEach() Loop Exercises
To count items meeting a specific condition using forEach(), set an initial count variable to zero and increment this counter conditionally within the loop. Example for counting even numbers: ```javascript let nums = [5, 10, 15, 20, 25, 30]; let evenCount = 0; nums.forEach(num => { if (num % 2 === 0) { evenCount++; } }); console.log(evenCount); ``` This iteration checks each number, increments evenCount for even numbers, and prints 3 .
The forEach() loop in JavaScript can access properties of each object within an array and perform operations such as manipulation or display. For instance, given an array of objects containing student details, one can extract and print just the name of each student: ```javascript let students = [ { name: "Kiran", age: 20 }, { name: "Rahul", age: 22 }, { name: "Sita", age: 21 } ]; students.forEach(student => { console.log(student.name); }); ``` This outputs: Kiran, Rahul, Sita .
The forEach() method is preferred when you need to perform side effects such as logging or modifying external variables due to its non-returning nature. In contrast, map() is used when you need to transform elements and utilize a new array result. forEach() is beneficial when operations do not require retaining transformed data within the context of the loop. For instance, printing or modifying an external counter without requiring an output array or ensuing chain calls, such as when printing personalized messages for an array of names, suits better with forEach().
The forEach() method in JavaScript is limited in its inability to return a value, unlike map() or filter(), making it less suitable for operations needing transformation into a new array or chaining subsequent operations. Since forEach() simply executes a provided function once for each array element without producing a transformed outcome, it is not suited for pipeline-like, chained operations. This makes it inefficient for transformations or when the combination of results needs further processing .
The forEach() method in JavaScript can be used to iterate over each element in an array and apply a function to each element. For instance, to output the square of numbers in an array, one could execute: ```javascript let numbers = [1, 2, 3, 4, 5]; numbers.forEach(number => { console.log(number * number); }); ``` This prints the squares of all numbers in the array [1, 4, 9, 16, 25].
The JavaScript forEach() method iterates over each element in the array and applies a specified operation or check. To count elements satisfying a condition, such as even numbers, a counter is incremented conditionally within the loop. For example: ```javascript let nums = [5, 10, 15, 20, 25, 30]; let evenCount = 0; nums.forEach(num => { if (num % 2 === 0) { evenCount++; } }); console.log(evenCount); ``` This code counts and prints 3 even numbers in the array .
The forEach() method is ideal for iterating over an array when the intention is to display or log information rather than manipulating data because it applies a function to each array element without returning a new array. For example, to print a greeting for each user: ```javascript let users = ["Anuj", "Riya", "Aman"]; users.forEach(user => { console.log(`Hello, ${user}!`); }); ``` This logs greetings for each user in the array .
A forEach() loop can facilitate complex data operations through conditional checks and property access during iteration. For filtering or conditional logging, a check is performed to decide which elements or properties to act upon during traversal. For example, printing names from an object array: ```javascript let students = [ { name: "Kiran", age: 20 }, { name: "Rahul", age: 22 }, { name: "Sita", age: 21 } ]; students.forEach(student => { if (student.age > 20) { console.log(student.name); } }); ``` This logs names for students older than 20: Rahul, Sita .
Yes, the forEach() method can modify original array elements by directly altering them. For instance, converting all uppercase names in an array to lowercase can directly modify the original array: ```javascript let names = ["RAHUL", "SITA", "ANUJ"]; names.forEach((name, index, namesArray) => { namesArray[index] = name.toLowerCase(); }); console.log(names); ``` This directly modifies names to ["rahul", "sita", "anuj"].
The forEach() method can traverse each element of a string array and apply a case transformation using methods like toLowerCase(). To convert an array of names from uppercase to lowercase: ```javascript let names = ["RAHUL", "SITA", "ANUJ"]; let lowerCaseNames = []; names.forEach(name => { lowerCaseNames.push(name.toLowerCase()); }); console.log(lowerCaseNames); ``` This transforms and prints ["rahul", "sita", "anuj"].