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

97
Views
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 answers
Answer question

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 Report

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 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!