0
0
Javascriptprogramming~20 mins

Block scope in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Block Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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();
A20\n10
B10\n20
C20\n20
D10\n10
Attempts:
2 left
πŸ’‘ Hint
Remember that let creates a new variable scoped to the block.
❓ Predict Output
intermediate
2: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);
}
A3 3 3 0 1 2
B0 1 2 0 1 2
C3 3 3 3 3 3
D0 1 2 3 3 3
Attempts:
2 left
πŸ’‘ Hint
var is function scoped, let is block scoped inside the loop.
🧠 Conceptual
advanced
2:00remaining
Block scope and closures
Consider this code:
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]());
Aundefined undefined undefined
B3 3 3
C0 1 2
D0 0 0
Attempts:
2 left
πŸ’‘ Hint
Each iteration has its own i because of let scoping.
❓ Predict Output
advanced
2:00remaining
Temporal Dead Zone error
What error does this code produce?
{
  console.log(a);
  let a = 5;
}
Javascript
{
  console.log(a);
  let a = 5;
}
ATypeError
BReferenceError
CSyntaxError
Dundefined
Attempts:
2 left
πŸ’‘ Hint
Variables declared with let are not accessible before declaration.
πŸ”§ Debug
expert
3: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?
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);
}
AMove setTimeout outside the for loop
BWrap setTimeout in an IIFE passing i as argument
CDeclare i with const instead of var
DReplace var with let in the for loop declaration
Attempts:
2 left
πŸ’‘ Hint
Block scope with let creates a new i each iteration.