Tech Study

JavaScript Recursion

Recursion is a programming technique in which a function calls itself until certain conditions are met. Recursion in JavaScript can be used to solve problems involving repeating a task or breaking a problem into smaller subtasks.

For recursive functions, a new execution context is created each time the function is called, and the function is called again with the changed input values.

Syntax:

function recursiveFunction(parameter) {

  if (baseCase) 

  {

  // handle base case


  else 

  {

    // modify parameter

    recursiveFunction(modifiedParameter);

  }

}

Example:

const fruits = ['apple', 'banana', 'orange', 'kiwi', 'pear'];

function eatFruit(fruitArray) {

  if (fruitArray.length === 0
  {

    console.log("No more fruits to eat!");

  } else {

    const currentFruit = fruitArray.shift();

    console.log(`Eating a ${currentFruit}`);

    eatFruit(fruitArray);

  }

}
eatFruit(fruits);

Output:

Eating a apple

Eating a banana

Eating a orange

Eating a kiwi

Eating a pear

No more fruits to eat!

In this example, the ‘eatFruit’ function takes an array of fruits as an argument and recursively eats each fruit in the array.

In the base case, there are no more fruits in the array, at which point the function outputs “No more fruits to it!” to the console.

Otherwise, the function removes the first fruit from the array using the ‘shift()’ method, prints a message saying that fruit is being eaten, and then calls itself with the modified fruit array.

This process continues until there are no fruits left in the array, at which point the base case starts and the recursion stops.

C String Functions

C String Functions perform certain operations, It provides many useful string functions which can come into action. The <string.h> header …

Read more

Function Pointer in C++

Introduction : Function Pointer in C++ Pointers: In function pointer in c++ are the variables that consist of addresses of …

Read more