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.

Java Final keyword

Introduction : java final keyword The final keyword present in Java programming language is generally used for restricting the user. …

Read more

C++ Memory Management: new and delete

C++ Memory Management We know that arrays store contiguous and the same type of memory blocks, so memory is allocated …

Read more