0

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);

4
  • 1
    you don't understand how map() works if you think that modifies the original array. What it does is it creates a new array Commented Apr 24 at 19:22
  • 1
    I'm sure there's a duplicate somewhere, but... You're not modifying anything in the array. You're modifying the local variable num, 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. Commented Apr 24 at 19:24
  • 1
    Consider if you did num = numbers[0]; num *= 2;. Would you expect that to modify numbers[0]? If not, why do you expect that to happen when num is a function parameter? Commented Apr 24 at 19:26
  • 1
    numbers.forEach((num,i,a) =>{a[i]=num*2}) Commented Apr 24 at 21:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.