Challenge - 5 Problems
Block Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of let inside block
What is the output of this code?
function test() {
let x = 10;
if (true) {
let x = 20;
console.log(x);
}
console.log(x);
}
test();Javascript
function test() { let x = 10; if (true) { let x = 20; console.log(x); } console.log(x); } test();
Attempts:
2 left
π‘ Hint
Remember that let creates a new variable scoped to the block.
β Incorrect
The inner let x = 20 shadows the outer x only inside the if block. So inside the block, console.log prints 20. Outside, it prints the original 10.
β Predict Output
intermediate2:00remaining
var vs let in loops
What is the output of this code?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 0);
}Javascript
for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); } for (let j = 0; j < 3; j++) { setTimeout(() => console.log(j), 0); }
Attempts:
2 left
π‘ Hint
var is function scoped, let is block scoped inside the loop.
β Incorrect
The var loop shares the same i variable, so all timeouts print 3 after the loop ends. The let loop creates a new j for each iteration, so timeouts print 0,1,2.
π§ Conceptual
advanced2:00remaining
Block scope and closures
Consider this code:
What is the output?
const funcs = [];
for (let i = 0; i < 3; i++) {
funcs.push(() => i);
}
console.log(funcs[0](), funcs[1](), funcs[2]());What is the output?
Javascript
const funcs = []; for (let i = 0; i < 3; i++) { funcs.push(() => i); } console.log(funcs[0](), funcs[1](), funcs[2]());
Attempts:
2 left
π‘ Hint
Each iteration has its own i because of let scoping.
β Incorrect
Using let in the loop creates a new i for each iteration, so each function remembers its own i value.
β Predict Output
advanced2:00remaining
Temporal Dead Zone error
What error does this code produce?
{
console.log(a);
let a = 5;
}Javascript
{
console.log(a);
let a = 5;
}Attempts:
2 left
π‘ Hint
Variables declared with let are not accessible before declaration.
β Incorrect
Accessing a let variable before its declaration causes a ReferenceError due to the temporal dead zone.
π§ Debug
expert3:00remaining
Fixing unexpected output with var in block
This code intends to print numbers 0 to 2 with delay, but prints 3 three times.
Which option fixes it?
Which option fixes it?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}Javascript
for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); }
Attempts:
2 left
π‘ Hint
Block scope with let creates a new i each iteration.
β Incorrect
Using let creates a new i for each loop iteration, so each timeout logs the correct value. The other options either cause errors or don't fix the problem.