0

print "0"

// Write code to calculate the average of an array // If there are no items in the array it should return 0 // NOTE: Create a function to find the sum of elements in an array and use that function to find out the average let x = [] let y = x.length let number=sum(y, x); function sum(a, b){ total=0; for(i=0;i<a;i++) total+=b[i]; return(total); } average = number/y; console.log(average) i want to print 0 but the output give me NaN how can i print 0 when my array is empty?

8th Jun 2022, 10:15 AM
TINKLE DASH
TINKLE DASH - avatar
4 Respuestas
+ 3
You could use an if-statement: if it is empty, print 0...
8th Jun 2022, 10:18 AM
Lisa
Lisa - avatar
+ 3
Why? If length is 0, dividing by 0 will produce nan.
8th Jun 2022, 10:29 AM
Lisa
Lisa - avatar
0
Other than that ?
8th Jun 2022, 10:25 AM
TINKLE DASH
TINKLE DASH - avatar
0
Yes I do with if else
8th Jun 2022, 10:44 AM
TINKLE DASH
TINKLE DASH - avatar