Average of an array?

Average of an array?
0

#1

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

#2

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


#3

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


#4

Put a single if statement which returns 0 if the array is empty. How do we know if an array is empty?


#5

There is, but try the if condition approach first and then I will guide you to the other way.


#6
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.


#7

Should you even enter the for loop if the array is empty?


#8
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;
}

#9

FYI - You can not compare an array to another array with ===. It will always return false.

If an array is empty, what property can we check to verify that it is empty?


#10

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


#11

When all else fails, do a search.


#12
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.


#13

Now, let’s shorten the code a bit.

Do you remember the FCC challenge named Falsy Bouncer? If not, review it first.

If statements evaluate an expression as either true or false no matter what is inside the ( ). Without testing it first, what do you think the following if statement would evaluate to if an empty array was passed into your average function?

if (numbers.length) {

#14

True? I would imagine.


#15

And why do you think that?


#16

There is something in the array? Regardless of value.


#17

If I pass an empty array, what is the value of numbers.length?


#18

Shit…NaN = false. Damnit


#19

numbers.length would evaluate to 0 which is a “falsy” value, so if you write:

if (0) {

the if statement evaluates to false, which is why if (numbers.length) { also evaluates to false if the array is empty.


#20

Gotcha. Thanks again