countdown recursion javascript code example

Example 1: Basic JavaScript: Use Recursion to Create a Countdown

function countdown(n){
  if (n < 1) {
    return [];
  } else {
    const arr = countdown(n - 1);
    arr.unshift(n);
    return arr;
  }
}
console.log(countdown(5)); // [5, 4, 3, 2, 1]

Example 2: countdown recursion javascript

const PrintAllChildren = tree => {  if (tree.children.length === 0) { //see if root (or recursive      return;                           iteration) node has children  }  tree.children.forEach(child => {     console.log(child.name);    printAllChildren(child); // execute the function on each child  });                            };

Example 3: countdown recursion javascript

const recursiveRangeSum = (num, total = 0) => {  if (num <= 0) {    return total;  }  return recursiveRangeSum(num - 1, total + num);};