// I want to add a number array elements but the result is showing Nan why so
let numarr = [5598, 4589 ,25465164]
let len = numarr.length;
let i, numval = 0;
for(i=0; i <= len; i++) {
numval += numarr[i];
}
document.getElementById("demo").innerHTML = numval;
It is because of the <= in for-loop. If you use <= then loop will run past the length of the array and it will try to access the element that is not present.
If you are trying to access the element that is not present then it will return undefined. Addition of a number with undefined will give you NaN
Either use numarr.length - 1 or i < len
let numarr = [5598, 4589, 25465164]
let len = numarr.length;
let i, numval = 0;
for (i = 0; i < len; i++) {
numval += numarr[i];
}
document.getElementById("demo").innerHTML = numval;
<h1 id="demo"></h1>
Alternate solution: You can also use reduce here to achieve the same result
let numarr = [5598, 4589, 25465164]
const numval = numarr.reduce((a, c) => a + c);
document.getElementById("demo").innerHTML = numval;
<h1 id="demo"></h1>
Your array has 3 elements at indices 0, 1 and 2. So your arrays should run from 0 to array.length - 1. If you tries to access numarr[3] the value will be undefined. Adding undefined to a number is NaN that means not a number
It should be i < len
let numarr = [5598, 4589, 25465164];
let len = numarr.length;
let i, numval = 0;
for (i = 0; i < len; i++) {
numval += numarr[i];
}
document.getElementById("demo").innerHTML = numval;
<div id="demo"></div>
The mistake you made has already been pointed out in numerous other answers, I would like to show you an alternative in modern JS.
Instead of using an index-based for-loop, Javascript has a specialized function for what you want to do, which is called Array.prototype.reduce. It is called once for each array element, adds its value to the accumulator and returns the accumulator after the last iteration. The start value 0 for the accumulator is the second parameter.
const numarr = [5598, 4589 ,25465164]
const sum = numarr.reduce((accumulator, value) => accumulator+value, 0);
document.getElementById("demo").innerHTML = sum;
<div id="demo"></div>