When i
, the index of the array nums
is out of bounds nums[i]
is undefined
. And when you add any undefined
to any number or NaN
the result is NaN
.
You can use nums[i+2] || 0
and nums[i+1] || 0
to avoid dealing with undefined
. If your aim is to sum all elements with an even index, 0,2 ..., and put the result in a
, a better approach might be as below. For a larger array you run the danger of adding some elements to the result more than once.
However, if that's your goal then you can retain nums[+2] || 0
and nums[i+1] || 0
.
const rob = function(nums) {
let a = 0;
let b = 0;
for (let i = 0; i < nums.length; i = i + 2) {
a += nums[i];
b += nums[i+1] || 0;
}
return a;
};
console.log(rob([1, 2, 3, 1]));