Scope & Hoisting — let, const, var and the TDZ — Concept Check
Questions on Scope & Hoisting — let, const, var and the TDZ. var is function-scoped and hoisted as undefined; let and const are block-scoped and hoisted into a temporal dead zone that throws if you touch them early. Use const by default, let when you must reassign, var never.
Questions in this quiz
8 questions on Scope & Hoisting — let, const, var and the TDZ — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.In a JavaScript loop using var, what will be logged by the following code? for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }
- A0, 1, 2
- B3, 3, 3
- C1, 2, 3
- D0, 0, 0
2.A developer declares a variable with let inside a block and tries to access it before its declaration. What happens?
- AIt returns null.
- BIt throws a ReferenceError.
- CIt returns undefined.
- DIt throws a TypeError.
3.What will happen if you try to reassign a const variable in JavaScript?
- AIt reassigns successfully.
- BIt throws a TypeError.
- CIt throws a ReferenceError.
- DIt silently fails.
4.Consider the code: if (true) { var x = 5; let y = 10; } What is the result of console.log(x) and console.log(y)?
- A5 and 10
- BReferenceError and ReferenceError
- CReferenceError and 10
- D5 and ReferenceError
5.A developer mistakenly believes const makes objects immutable. What happens when modifying a property of a const object?
- AThe change is silently ignored.
- BThe property changes successfully.
- CIt throws a TypeError.
- DIt throws a ReferenceError.
6.In JavaScript, what is the main difference between var and let in terms of scope?
- Avar is function-scoped, let is block-scoped.
- BBoth are function-scoped.
- Cvar is block-scoped, let is function-scoped.
- DBoth are block-scoped.
7.What will be logged by the following code? console.log(a); var a = 1;
- ATypeError
- B1
- CReferenceError
- Dundefined
8.Why does the following code throw an error? console.log(b); let b = 1;
- Ab is block-scoped.
- Bb is not declared.
- Cb is not initialized to undefined.
- Db is in the temporal dead zone.