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

175
Views
why recursion function returns "NaN" here

I have to find the sum of the absolute difference between consecutive elements of the array. But sumAbsArr function returns nun

var arr = [1, 5, 2];
var n = 3;
var cur = 0;

console.log(sumAbsArr(arr, n, cur))

function sumAbsArr(arr, n, cur) {
  if (n == cur) {
    return 0
  }
  var abs = Math.abs(arr[cur] - arr[cur + 1])
  var ans = abs + sumAbsArr(arr, n, cur + 1)
  return ans
}

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

0

I think you are wrong at placing the condition. Look at arr[cur+1] (at line 11), when cur = 3 the cur+1 is out of range (arr index is start at 0 and end at arr.length-1 which is 2). So to prevent arr[cur+1] have NaN value, you have to change the condition

var arr = [1, 5, 2];
var n = 3;
var cur = 0;

console.log(sumAbsArr(arr, n, cur))

function sumAbsArr(arr, n, cur) {
  // change the condition to stay within the range
  if (cur == n-1) { 
    return 0
  }
  var abs = Math.abs(arr[cur] - arr[cur + 1])
  var ans = abs + sumAbsArr(arr, n, cur+1)
  return ans
}

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!