JS Recursion? Recurison()

지원 ·2023년 5월 8일
0

What is recursion?

Process that calls itself (A function that calls itself)

Note: When JavaScript sees the return keyboard, the compiler will remove.

How recursion works

Inoke the same function with a different input until you reach base case.

Base case

The condition when the recursion ends.

if(num === 1) return 1; 

Recursion function example

Loops the numbers 3.. 2... 1.. then 0 which outputs 'Done'

function countDown(num) {
	if(num <= 0) {
		console.log('Done')
		return;
	}
	num--; 
	countDown(num) 
}

countDown(5) 

countDown(3) print 3... countDown(2) print 2... countDown(1) print 1...

Then it finally reaches countDown(0) which is the base case.


Recursive example #2

base case

num === 1 return 1;

finding the sum range (num + num(1))

function sumRange(num) {
	if (num === 1) return 1;
	return num + factorial(num - 1);
}

sumRange(5) // 120 ( 5 * 4 * 3 * 2 1 )

The process

factorial(3)
return 3 + sumRange(2) 
return 2 + sumRange(1) 
return 1 

(Backwards)

return 1;			sumRange(1) === 1
return 2 + 1 			2 + sumRange(1) which is 1 so 2 + 1
return 3 + 3 ; 			3 + sumRange(2) which is 3 (2 + 1) 	

so the final output is 6 

0개의 댓글