JavaScript Interview: Run loop without pre-determined method


This year I gave an interview at some organization and I was asked this question:

Run a loop without using any pre-determined method or loops.

Using recursion is the way to go!
Here’s an example of how you can create a simple loop using recursion:

function customLoop(counter, limit) {
  // Base case: exit the recursion when the counter exceeds the limit
  if (counter > limit) {

  // Your loop logic goes here

  // Recursive call to increment the counter and continue the loop
  customLoop(counter + 1, limit);

// Example: Run the loop from 1 to 5
customLoop(1, 5);

In this example, the customLoop function takes a counter and a limit. It prints the value of the counter and then calls itself with an incremented counter until the counter exceeds the limit, at which point the recursion stops.

Note that using recursion for loops may not be the most efficient solution in all cases, and it may have limitations due to the maximum call stack size. However, it serves the purpose of demonstrating how to create a loop without using traditional loop constructs.

Follow me for more such content:

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

Five Quality Companies to Know: DIT-MCO International

Next Post

Taming the Flame: Securely Connecting Next.js and Firebase with TypeScript

Related Posts