Javascript Recursion Samples
JS
S
JavaScript2 Examples of recursion
1/* Stack: LIFO: “Last In, First Out”
2 function call() => an execution context gets placed on the execution stack
3
4 Execution Contexts:
5 STACK: [ global context, fn1 context, fn2 context, fn3 context ]
6
7 Execution Context
8 - Activation Object (parameters, variables and functions)
9 - 'this' pointer
10
11 callMe(); //last to be added, first to be called
12 STACK:
13 [ global context, fn1 context, fn2 context, fn3 context, callme context ]
14 [ global context, fn1 context, fn2 context, fn3 context ] <<
15 [ global context, fn1 context, fn2 context ] <<
16 [ global context, fn1 context ]
17 [ global context ]
18
19 Recursion:
20 Wait for return values from other execution contexts.
21 Divide-and-conquer approach to solve problems
22
23 A recursion without an exit condition will cause a Stack Overflow (no more memory on the stack), because we are adding execution contexts on the top of the stack
24*/
25
26// ------------------------------------------------------------------------------
27// product of all positive integers less than or equal to its argument.
28const factorial = (num) => {
29 debugger;
30 if (num === 0 || num === 1) {
31 return 1
32 } else {
33 return num * factorial(num - 1)
34 }
35}
36
37/*
38 Factorial Execution Contexts Stack State Overview
39 [ 5*fn(4), 4*fn(3), 3*fn(2), 2*fn(1), 1]
40 OK Stack pushes complete
41 Note: Stack is LIFO
42 (1) > (2x1) > (3x2) > (4x6) > (5x24)
43*/
44
45// const res = factorial(5);
46// console.log({res})
47
48
49// ------------------------------------------------------------------------------
50const fibonacci = function(num) {
51 if (num <= 1) {
52 return num
53 } else {
54 return fibonacci(num - 1) + fibonacci(num - 2)
55 }
56}
57fibonacci(5);
58
59/*
60 Factorial Execution Contexts Stack State Overview
61 [ 5*fn(4), 4*fn(3), 3*fn(2), 2*fn(1), 1]
62 OK Stack pushes complete
63 Note: Stack is LIFO
64 (1) > (2x1) > (3x2) > (4x6) > (5x24)
65*/Created on 2/21/2022