Recursive functions. JavaScript code example open

Recursive functions. JavaScript code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

A recursive function in JavaScript is a function that calls itself within its body. Recursion is a powerful tool for solving problems that can be broken down into smaller subproblems.

Recursive function example:

function countdown(num) {
  if (num <= 0) {
    console.log("Done!");
  } else {
    console.log(num);
    countdown(num - 1);
  }
}

countdown(5);

Calling countdown(5) will print a sequence of numbers from 5 to 1 to the console, followed by the message “Done!“.

This example uses the countdown function to count down from a given number to zero. If num is less than or equal to zero, the function displays the message “Done!“.

Otherwise, it prints the current number and calls itself with the argument num – 1.

Recursive functions can be useful for solving problems such as calculating a factorial, searching for elements in a tree, or traversing data structures.

However, it is important to be careful when using recursion to avoid an infinite loop and to correctly define a base case that will stop recursive calls.
0

More

Leave a Reply

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

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation