Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

211
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda