Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a for of loop to calculate multiply elements in an array

I'm a newbie to JavaScript and I have an exercise about for...of but it failed. It returned NaN.

Where am I doing wrong and what do I need?

Code:

var arr = [];

function multiply(arr) {
  for (var a of arr) {
    a *= arr[a];
  }
  return a;
}
console.log(multiply([2, 3, 4])); // expect: 24
like image 336
Hoang Dinh Avatar asked Dec 30 '25 18:12

Hoang Dinh


1 Answers

See your code modified below. Now working:

var arr = undefined;

function multiply(arr) {
  if (!arr || !arr.length) {     // if the array is undefined or has no elements, return null
      return null;
  }                              // otherwise, continue to do the calculation, it's an array with values
  var result = 1;                // start our result in 1
  for (var a of arr) {
    result *= a;                 // increase the result by multiplying the
                                 // previous value for every value in the array
  }
  return result;                 // finally return
}
console.log(multiply([2, 3, 4])); // expect: 24
console.log(multiply([]));        // expect: null: 0 elements
console.log(multiply(arr));       // expect: null: arr var is undefined
console.log(multiply());          // expect: null: no argument provided
like image 191
lealceldeiro Avatar answered Jan 01 '26 11:01

lealceldeiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!