Challenge - 5 Problems
Scope Chain Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of nested function with variable shadowing
What is the output of this JavaScript code?
Javascript
let x = 10; function outer() { let x = 20; function inner() { console.log(x); } inner(); } outer();
Attempts:
2 left
π‘ Hint
Remember that inner functions look for variables in their own scope first, then outer scopes.
β Incorrect
The inner function finds the variable x in the outer function's scope, which is 20, so it prints 20.
β Predict Output
intermediate2:00remaining
Output of var in for loop with setTimeout
What will be logged to the console when this code runs?
Javascript
for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); }
Attempts:
2 left
π‘ Hint
Consider how var variables are scoped and when the callbacks run.
β Incorrect
The var variable i is function-scoped, so by the time the callbacks run, i is 3, so it logs 3 three times.
β Predict Output
advanced2:00remaining
Output of let in for loop with setTimeout
What will be logged to the console when this code runs?
Javascript
for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); }
Attempts:
2 left
π‘ Hint
Think about how let variables are scoped in loops.
β Incorrect
The let variable i is block-scoped and a new binding is created each loop iteration, so the callbacks log 0, 1, and 2 respectively.
β Predict Output
advanced2:00remaining
Output of variable lookup with nested scopes
What is the output of this code?
Javascript
const a = 1; function f1() { const a = 2; function f2() { console.log(a); } f2(); } f1();
Attempts:
2 left
π‘ Hint
Inner functions use the closest variable in their scope chain.
β Incorrect
The inner function f2 finds a in f1's scope which is 2, so it logs 2.
π§ Conceptual
expert2:00remaining
Scope chain and variable resolution order
Given the code below, what value will be logged to the console?
Javascript
let x = 5; function outer() { let x = 10; function inner() { let x = 15; console.log(x); } inner(); } outer();
Attempts:
2 left
π‘ Hint
Variables are resolved starting from the innermost scope outward.
β Incorrect
The inner function has its own x variable set to 15, so it logs 15.