DEV Community

Shameel Uddin
Shameel Uddin

Posted on

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) {
    return;
  }

  // Your loop logic goes here
  console.log(counter);

  // 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);
Enter fullscreen mode Exit fullscreen mode

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:
YouTube: https://www.youtube.com/@ShameelUddin123
LinkedIn: https://www.linkedin.com/in/shameeluddin/
Github: https://github.com/Shameel123

Top comments (0)