javascriptadvanced10 minutes
Predict the Output of Nested Closures and Asynchronous Execution in JavaScript
Analyze a complex JavaScript function involving nested closures, asynchronous setTimeout calls, and variable shadowing to predict the exact console output sequence and values.
Challenge prompt
Examine the following JavaScript code snippet. Predict the exact output printed to the console when this code runs. Explain the sequence and reasoning for each output line, considering closures, variable scope, and asynchronous execution.
Guidance
- • Pay close attention to variable scopes, especially how let and var behave in closures.
- • Analyze how setTimeout callbacks capture variables and when they execute relative to the main thread.
- • Consider how the loop variables are captured by the closures inside the asynchronous callbacks.
Hints
- • Remember that 'var' has function scope and 'let' has block scope, affecting closure capture.
- • setTimeout callbacks queued with zero delay still run after the synchronous code completes.
- • Think about how changes to loop variables affect closures differently for var vs let.
Starter code
function trickyClosure() {
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log('var loop i:', i);
}, 0);
}
for (let j = 0; j < 3; j++) {
setTimeout(function() {
console.log('let loop j:', j);
}, 0);
}
(function() {
for (var k = 0; k < 3; k++) {
setTimeout(function() {
console.log('IIFE var k:', k);
}, k * 10);
}
})();
}
trickyClosure();Expected output
var loop i: 3 var loop i: 3 var loop i: 3 let loop j: 0 let loop j: 1 let loop j: 2 IIFE var k: 3 IIFE var k: 3 IIFE var k: 3
Core concepts
closuresvariable scopeasynchronous execution
Challenge a Friend
Send this duel to someone else and see if they can solve it.