What does NaN mean? And how do I remove it from my code ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

What does NaN mean? And how do I remove it from my code ?

var result, i, arr; arr = [1,2,3,4,5]; flax = arr.length; for (i=0; i < flax; i++){ result+=arr[i]; } //Output: NaN

22nd Jan 2018, 1:06 AM
The Kid
The Kid - avatar
8 Answers
+ 15
You have to initialise your variable: var result = 0 Else, depending on how JS works, result may not even be interpreted as a number.
22nd Jan 2018, 1:11 AM
Hatsy Rei
Hatsy Rei - avatar
+ 18
NaN-> Not a Number....
22nd Jan 2018, 1:10 AM
Jaydeep Khatri
Jaydeep Khatri - avatar
+ 11
There is no print element in the code.....
22nd Jan 2018, 1:24 AM
Jaydeep Khatri
Jaydeep Khatri - avatar
+ 5
NaN stands for Not a Number. In arr variable, you have stored 1,2,3,4 and 5. Now you want to add them by a for loop and store the result in result variable. You have defined the result variable but you haven't stored any data in it. That means " result = undefined " When you run the program result = undefined + 1 + 2 + 3 + 4 +5 So, the result = NaN. But if you store 0 in result variable, it will output 0 + 1 + 2 + 3 + 4 +5 = 15.
22nd Jan 2018, 2:03 AM
Adnan Zawad Toky
Adnan Zawad Toky - avatar
+ 4
// Fixed variant var result = 0; var arr = [1,2,3,4,5]; var flax = arr.length; for (i=0; i < flax; i++){ result+=arr[i]; } alert(result);
22nd Jan 2018, 2:09 AM
Boris Batinkov
Boris Batinkov - avatar
+ 3
@N/A, Hatsy's solution should work. Try to declare flax as well.
22nd Jan 2018, 1:21 AM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 2
@Hatsy Rei, I did what u said but now it returns 0 instead of the sum.
22nd Jan 2018, 1:15 AM
The Kid
The Kid - avatar
+ 2
@Jaydeep isnt that dom ?
22nd Jan 2018, 1:19 AM
The Kid
The Kid - avatar