The forEeach method in JavaScript is an array method used to execute a provided function once for each element in an array. It’s beneficial when you want to perform side effects such as logging, updating each element in place, or calling functions that do not require returning a new array.
Syntax:
array.forEach(function(element, index, array) {
// Your code here
}, thisArg);
element: The current element being processed in the array.
index (optional): The index of the current element being processed.
array (optional): The array forEach was called upon.
thisArg (optional): A value to use as this when executing the callback function.
Characteristics of forEach
1. Does Not Return a Value: The forEach method always returns undefined. It doesn’t return a new array, unlike some other array methods like map.
2. Iterates Over Every Element: The function passed to forEach is executed for every element of the array, even if it is undefined, null, or an empty slot.
3. Cannot Be Interrupted: You cannot break out of a forEach loop using break or continue. If you need to stop iteration based on a condition, consider using a for loop or the some or every methods.
4. Modifying the Array: You can modify the original array within the forEach loop by directly altering its elements.
Example: Modify the array element
const numbers = [1, 2, 3, 4];
numbers.forEach((num, index, arr) => {
arr[index] = num * 5; // multiply by 5 for each element in the original array
});
console.log(numbers); // Output: [5, 10, 15, 20]
forEach method – Interview Questions
Q 1: What is the forEach() method?
Ans: forEach() executes a callback function once for each array element.
Q 2: Does forEach() return a value?
Ans: No, it always returns undefined.
Q 3: Can forEach() break the loop?
Ans: No, break and return cannot stop it.
Q 4: Does forEach() modify the original array?
Ans: It does not create a new array, but elements can be modified.
Q 5: Is forEach() asynchronous?
Ans: No, it runs synchronously.
forEach method– Objective Questions (MCQs)
Q1. forEach() is used to ______.
Q2. Does forEach() return a value?
Q3. forEach() can access which parameters?
Q4. Can break be used inside forEach()?
Q5. forEach() executes callback for ______ elements.