Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

347
Views
what are the mistake in this code, its giving me NaN

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]));

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

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.

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report

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]));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!