Web Developer Interview Preparation

Recursion

Definition Recursion is a programming concept, which happens when a function calls itself. It is used in a mathematical problem solving and a logical solution.

function sayHeeya() {
      console.log("Hi heeya");
      sayHeeya();
}
sayHeeya();
This function is calling itself, and it is a dangerous as it is calling itself indefinitely. Therefore, we need to define the exiting condition, which we call a ‘base case’. Every recursive function needs to have it to exit a function properly when a condition is met.
function sayHeeya(count) {
if (count == 0){
   return;
}
console.log("Hi heeya");
   sayHeeya(count - 1);
}
sayHeeya(10);
Each one of the functions copies will have a new set of internal variables called a stack. Now without a base case JavaScript will continue to ask for new variables until it either runs out of memory or the browser runs into an internal limit. Now when the computer runs out of memory that’s called a stack overflow. (Villalobos)
Recursion is very useful when the current call relies on the result of the previous call.
function twoToThePowerOf(number) {
	if (number == 0) {
		return 1;
	} else {
		return 2 * twoToThePowerOf(number - 1);
	}
}
console.log(twoToThePowerOf(2));
2 ^ 5 = 2 * (2 ^ 4)
      =  2 * 2 * (2 ^ 3)
      =  2 * 2 * 2 * (2 ^ 2)
      =  2 * 2 * 2 * 2 * (2 ^ 1)
      =  2 * 2 * 2 * 2 * 2 * (2 ^ 0)
      =  2 * 2 * 2 * 2 * 2 * 1
Now, let’s take a look at the typical interview question for recursion. Calculating Fibonacci number. [What is the Fibonacci number?]
function fibonacci(number) {
	if (number == 0 || number == 1) {
		return 1;
	} else {
		return fibonacci(number - 1) + fibonacci(number - 2);
	}
}
console.log(fibonacci(9));
// 55
Reference When would you use recursion? Mastering Web developer Interview Code – Ray Villalobos, Lynda.com LINK]]>

Leave a Reply

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