Uploaded December 2019 | Updated September 2026, 2 weeks ago
We start with the JavaScript code for generating the n-th factorial using recursion and memoization, and visualize the step-by-step execution using JavaScript tutor.
Learn more on Khan Academy: Learn more on Khan Academy: khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/improving-efficiency-of-recursive-functions
Try it yourself here:
pythontutor.com/javascript.html#code=var%20memo%20%3D%20%7B%7D%3B%0Avar%20factorial%20%3D%20function%28n%29%20%7B%0A%20%20%20%20if%20%28n%20%3D%3D%3D%200%29%20%7B%0A%20%20%20%20%20%20%20%20return%201%3B%0A%20%20%20%20%7D%20else%20if%20%28memo.hasOwnProperty%28n%29%29%20%7B%0A%20%20%20%20%20%20%20%20return%20memo%5Bn%5D%3B%0A%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20var%20result%20%3D%20factorial%28n%20-%201%29%20*%20n%3B%0A%20%20%20%20%20%20%20%20memo%5Bn%5D%20%3D%20result%3B%0A%20%20%20%20%20%20%20%20return%20result%3B%0A%20%20%20%20%7D%0A%7D%3B%0A%0Afactorial%282%29%3B%0Afactorial%285%29%3B&curInstr=41&mode=display&origin=opt-frontend.js&py=js&rawInputLstJSON=%5B%5D
We start with the JavaScript code for generating the n-th factorial using recursion and memoization, and visualize the step-by-step execution using JavaScript tutor.
Learn more on Khan Academy: Learn more on Khan Academy: khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/improving-efficiency-of-recursive-functions
Try it yourself here:
pythontutor.com/javascript.html#code=var%20memo%20%3D%20%7B%7D%3B%0Avar%20factorial%20%3D%20function%28n%29%20%7B%0A%20%20%20%20if%20%28n%20%3D%3D%3D%200%29%20%7B%0A%20%20%20%20%20%20%20%20return%201%3B%0A%20%20%20%20%7D%20else%20if%20%28memo.hasOwnProperty%28n%29%29%20%7B%0A%20%20%20%20%20%20%20%20return%20memo%5Bn%5D%3B%0A%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20var%20result%20%3D%20factorial%28n%20-%201%29%20*%20n%3B%0A%20%20%20%20%20%20%20%20memo%5Bn%5D%20%3D%20result%3B%0A%20%20%20%20%20%20%20%20return%20result%3B%0A%20%20%20%20%7D%0A%7D%3B%0A%0Afactorial%282%29%3B%0Afactorial%285%29%3B&curInstr=41&mode=display&origin=opt-frontend.js&py=js&rawInputLstJSON=%5B%5D










