javascriptadvanced10 minutes
Predict Output: Complex Recursive Function with Memoization and Side Effects
Analyze the given JavaScript code involving recursion, memoization, and side effects, and predict what the output will be when it is executed.
Challenge prompt
Examine the provided JavaScript function which computes a value recursively and uses memoization alongside side effects that mutate an external array. Determine exactly what will be printed to the console when the function is called with the argument 5.
Guidance
- • Trace the recursive calls carefully to understand the order in which results are computed.
- • Consider how the memoization cache is updated and accessed during calls.
- • Analyze the side effects on the external array and how they affect the final output.
Hints
- • Pay close attention to when elements are pushed into the external array and how that corresponds to the recursive unwind.
- • Remember that the function modifies state outside its local scope during execution, affecting console output.
- • Think about the behavior of short-circuit evaluation with logical operators in JavaScript.
Starter code
const cache = {};
const sideEffectArray = [];
function complexFunc(n) {
if (cache[n] !== undefined) return cache[n];
if (n <= 1) {
sideEffectArray.push(n);
return n;
}
const result = complexFunc(n - 1) + complexFunc(n - 2);
sideEffectArray.push(result);
cache[n] = result;
return result;
}
console.log(complexFunc(5));
console.log(sideEffectArray);Expected output
5 [1, 0, 1, 2, 3, 5]
Core concepts
recursionmemoizationside effectsJavaScript evaluation order
Challenge a Friend
Send this duel to someone else and see if they can solve it.