JavaScript Interview: Run loop without pre-determined method

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);

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

Total
0
Shares
Leave a Reply

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

Previous Post
five-quality-companies-to-know:-dit-mco-international

Five Quality Companies to Know: DIT-MCO International

Next Post
taming-the-flame:-securely-connecting-next.js-and-firebase-with-typescript

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

Related Posts