I’m trying to double each number in an array using forEach, but the original array isn’t changing. Here’s my code:
const numbers = [1, 2, 3];
numbers.forEach((num) => {
num = num * 2; // Doubling the value
});
console.log(numbers); // Output: [1, 2, 3] (unchanged)
Expected Output:
[2, 4, 6]
What I’ve Tried:
Used map() instead (works, but I want to understand forEach).
Tried accessing the array by index:
numbers.forEach((num, index) => {
numbers[index] = num * 2; // This works, but why doesn’t the first approach?
});
console.log(numbers);
map()works if you think that modifies the original array. What it does is it creates a new arraynum, which then immediately falls out of scope when the callback function ends. Note in your later example you directly modify the array value, not the function-local variable.num = numbers[0]; num *= 2;. Would you expect that to modifynumbers[0]? If not, why do you expect that to happen whennumis a function parameter?numbers.forEach((num,i,a) =>{a[i]=num*2})