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

209
Views
Recursion in Js

Can someone please explain to me why we need (n-1) in the following code.

  function multiply(arr, n) {
    if (n <= 0) {    
      return 1;
    } else {
      return multiply(arr, n - 1) * arr[n - 1];
    }
  }

I understand that we have a base case of if (n <= 0){return 1} inorder for the code to not loop for ever but I dont understand the (n-1) and [n-1] in the recursive case of return multiply(arr, n - 1) * arr[n - 1]; .

Any help is much appreciated.

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

0

It looks like this function is meant to start with the last element of the array and recursively operate on each earlier element. This is why when calling the function recursively, you must pass in the next earlier element, i.e. n-1. This moves the function closer to the base case with each iteration.

about 4 years ago · Juan Pablo Isaza Report

0

The function could be improved, but you can understand it as-is by adding some debug logging...

function multiply(arr, n) {
  if (n <= 0) {
    return 1;
  } else {
    console.log(`recurse to multiply ${arr[n-1]} by elements in [${arr.slice(0,n-1)}]`);
    return multiply(arr, n - 1) * arr[n - 1];
  }
}

multiply([1, 2, 3], 3);

A clearer implementation wouldn't require the length param, and be clearer about decomposition...

// if the array has a first element, multiply it by the remainder of the array
function multiply(arr) {
  return arr.length ? arr[0] * multiply(arr.slice(1)) : 1;
}

console.log(multiply([1,2,3]))

about 4 years ago · Juan Pablo Isaza Report

0

This function just multiplies all elements of the given array. Initially you must pass the array and it's length as n.

The last element for any array is n-1. Thus on the 1st iteration it will take the last element and multiply further until it reaches 0. Then it will stop.

Just try to run this function mentally in your head on some simple examples and you'll get it.

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!