1

I'm trying to write a function to calculate the elements average in an array using the parameter (...rest)

Here what I've tried:

function average(...nums) {
  let total = 0;
  
  for (const num of nums) {
    total += num;
  }
  
  return total / nums.length;
}

console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
console.log(average());

But the last test returns NaN and I don't know why.

adiga
  • 34,372
  • 9
  • 61
  • 83

6 Answers6

2

Because you're trying to divide 0 (total) by 0 (nums.length where nums is []), which is NaN in JavaScript.

You can have a check at the top of your function that returns a default value (say, 0), if the list is empty:

function average(...nums) {
    if (!nums.length) return 0;
    let total = 0;
    // rest
}
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
1

You are returning 0/0 (which is NaN) when you pass nothing in, as nums becomes an empty array. and its length becomes 0.

You should return nums.length ? total/nums.length : 0;

Abishek Aditya
  • 802
  • 4
  • 11
1
function average(...nums)
{
    let total = 0;  
    for(const num of nums)
    {
        total +=num;
        n= nums.length;
    }
    return total/n;
}

console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
console.log(average());
derloopkat
  • 6,232
  • 16
  • 38
  • 45
0

Check it the argument which is an array exists, if not return 0 or some value stating that average cannot be calculated.

function average(...nums) {
  if (!nums.length) {
    return 'Cannot find average'
  }
  let total = 0;
  for (const num of nums) {

    total += num;
  }
  return total / nums.length;
}

console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
console.log(average());
EugenSunic
  • 13,162
  • 13
  • 64
  • 86
0

function average(...inputs) {
    let avg = 0;
    let sum = 0;
    for(const input of inputs){
        sum += input;
    }
    avg = sum / inputs.length;
    return avg;
}

console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
console.log(average());
0

The answer what you have provided will return NAN. So to avoid this get the length of the array/set of data and then divide the total only if the length is greater then 0.

function average(...value) {
    let total =0;
    for(const argument of value) {
    total += argument;
  }
  return  value.length>0?total/value.length : total;
}

console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
console.log(average());
Abishek
  • 1
  • 1