Search code examples
javascriptarraysundefinedmultiplication

Multiplying elements in arrays using the forEach function


I'm currently learning about arrays and the different ways to manipulate them. I was asked to: "multiply 5 to the given array using the forEach function"

Here is my code so far.

It looks as if everything works when I console.log in the forEach function, but when I log the console for the array it's read as undefined.

let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];

function multiplyNumbers() {
  let numbers;
  multiplyArray.forEach(function(element) {
    let fiveTimesNum;
    fiveTimesNum = (element * 5);
    element = fiveTimesNum;
    console.log(element)
  });
  console.log('The array(element) value is read out correctly, but when I console log the array its value is ↓')
  return numbers
}
multiplyArray = (multiplyNumbers());
console.log(multiplyArray);


Solution

  • If you want to change the array multiplyArray in place you can it like this:

    let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];
    
    multiplyArray.forEach(function(n,i,a){a[i]=5*n;});
    
    console.log(multiplyArray);