 # 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;
}
``````
1 Like

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?

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

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

1 Like
``````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.

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

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

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?

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

When all else fails, do a search.

1 Like
``````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.

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) {
``````

True? I would imagine.

And why do you think that?

There is something in the array? Regardless of value.

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

Shit…NaN = false. Damnit

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.

Gotcha. Thanks again