0
0
Javascriptprogramming~20 mins

Scope chain in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Scope Chain Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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();
A10
B20
Cundefined
DReferenceError
Attempts:
2 left
πŸ’‘ Hint
Remember that inner functions look for variables in their own scope first, then outer scopes.
❓ Predict Output
intermediate
2: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);
}
A0 1 2
B0 0 0
Cundefined undefined undefined
D3 3 3
Attempts:
2 left
πŸ’‘ Hint
Consider how var variables are scoped and when the callbacks run.
❓ Predict Output
advanced
2: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);
}
Aundefined undefined undefined
B3 3 3
C0 1 2
D0 0 0
Attempts:
2 left
πŸ’‘ Hint
Think about how let variables are scoped in loops.
❓ Predict Output
advanced
2: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();
A2
B1
Cundefined
DReferenceError
Attempts:
2 left
πŸ’‘ Hint
Inner functions use the closest variable in their scope chain.
🧠 Conceptual
expert
2: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();
A15
B10
C5
DReferenceError
Attempts:
2 left
πŸ’‘ Hint
Variables are resolved starting from the innermost scope outward.