Average of an array?

I have it all passing except I need it to return 0 instead of NaN if my array is empty.

function average (numbers) {
  let sum = 0;
  for (let i = 0; i < numbers.length; i++){
      sum += numbers[i];
  }
  return sum / numbers.length;
}

Why don’t you check if the array is empty and return if so?

Certainly there is an easier way for it to pass without some ridiculous condition?

function average (numbers) {
  let sum = 0;
  for (let i = 0; i < numbers.length; i++){
      sum += numbers[i];
      if(arr === []){
          return sum;
      }
  }
  return sum / numbers.length;
}

Not sure if this is it.

function average (numbers) {
  let sum = 0;
    if(numbers === []){
          return sum;
        
    }
  for (let i = 0; i < numbers.length; i++){
      sum += numbers[i];
  }
  return sum / numbers.length;
}

Array.find()? I’m not sure.

function average (numbers) {
  let sum = 0;
    if(numbers.length === 0){
          return sum;
        
    }
  for (let i = 0; i < numbers.length; i++){
      sum += numbers[i];
  }
  return sum / numbers.length;
}

Thanks, guys.

True? I would imagine.

There is something in the array? Regardless of value.

Shit…NaN = false. Damnit

Gotcha. Thanks again

Funny enough, with that shortened code, it doesn’t pass in this console they gave us. The longer version does.

function average (numbers) {
  let sum = 0;
    if(0){
          return sum;
        
    }
  for (let i = 0; i < numbers.length; i++){
      sum += numbers[i];
  }
  return sum / numbers.length;
}

I’m just confused because I solved it already and we are trying to make it shorter?

Damn, I was just so confused. Thanks

I’m trying that in the other thread I just made about sum. Still struggling…

I was just looking for an answer for another challenge and came across with this conversation. I love the way RandellDawson guides rstorms to the solution(s). While I was trying to find an answer for my problem but now I’ve got stuck with another.
How “numbers.length” in if(numbers.length) is a condition and is it evaluated? 0 returns false but if there is any other number like if(3) returns true. What is the logic behind it? if there is no condition should it not return an error?

when you put something as condition of an if statement, that value is coerced to a boolean, so falsy values (0, '', [], false, NaN, null, undefined) are evaluated as false, everything else as true. there is also the logical NOT operator, that flips the bolean value of whatever is put in front of it, if(!numbers.length) - if numbers.length is 0 the statement is executed because the ! makes the condition true

thank you for your reply ieahleen.

Why you wanna enter the loop ? Just check the array length first in top of the function.