-1

Why this code giving me NaN as an output???

var rob = function(nums) {
  var a = 0;
  var b = 0;
  for (let i = 0; i < nums.length; i++) {
    a += nums[i] + nums[i + 2]
    b += nums[i + 1] + nums[i + 2]
  }
  return a
};
console.log(rob([1, 2, 3, 1]));
VLAZ
  • 26,331
  • 9
  • 49
  • 67
srig
  • 1
  • 3
    What do you think `nums[i + 2]` would give for `i = 3`? Also see: [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – VLAZ Jun 12 '22 at 13:52

3 Answers3

0

You iterate through the array nums and then trying to access its members beyond its last element.

When i is 3, nums[i+2] refers to nonexisting element, yielding undefined, and when you add a number to undefined, you get NaN.

punund
  • 4,321
  • 3
  • 34
  • 45
0

There are four items in the array [1, 2, 3, 1]. The issue is i+2.

In third iteration of the loop, you are trying to access an index that doesn't exist: nums[i + 2] in third iteration becomes nums[2 + 2], which becomes nums[4]. But nums[3] is the last item, because the array length is only 4

Mads Akselsen
  • 249
  • 1
  • 5
0

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]));
PeterKA
  • 24,158
  • 5
  • 26
  • 48