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

98
Vistas
Qn-print and write all array element using recursion in JavaScript cuz i'm new to the concept of recursion i couldn't able to figure out the problem

Here is my code and I know there is some mistake in my code but I'm new to the concept of recursion. I think there is a problem cuz I tried to implement the same code as the C language. I want my answer to read and print array by using recursion And I tried to convert the c code into javascript, c++ code into javascript and lastly in python code into javascript.

var a = [1, 2, 3];
var l = a.length;
var num = 0;

function printArr(a, i, l){
  for(var i=0; i<l; i++){
    num = a[i];
  }
  if(i>=l){
    return 0;
    printArr(a, i+1, l);  //<I think in this section I'm having a problem.>
  }
}

printArr(a, 0, l); 
console.log(num);   
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

No need for that for loop.

Your printArr call should be outside if statement.

var a = [1, 2, 3];
var l = a.length;
//var num = 0; // not needed

function printArr(a, i, l) {
  // Base condition - to break out of recursion
  // check if index is out of array bounds, if yes return
  if (i >= l) {
    return;
  }

  // if not, print the array element at that index
  console.log(a[i]);

  // call the recursive function with next consecutive index
  printArr(a, i + 1, l);
}

printArr(a, 0, l);  

about 4 years ago · Juan Pablo Isaza Denunciar

0

Another method would allow us to avoid mucking about with indices at all, destructuring the input array and checking whether the first element is empty:

const printArr = ([x, ...xs]) => {
  if (x == null) return null
  console .log (x)
  return printArr (xs)
}

printArr ([1, 2, 3])

I would personally prefer to write this as a single expression, like this:

const printArr = ([x, ...xs]) => 
  x == null ? null : (console .log (x), printArr (xs))
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