Fifteen multiple-choice questions on JavaScript variables: function and block scope, hoisting, the temporal dead zone, redeclaration, const objects, Object.freeze and loop bindings. Pick an option to check your answer instantly.
Question 11Hard
What happens when console.log(typeof token); runs on the line just before let token = "abc"; in the same scope?
AIt prints undefined
BIt prints string
CA ReferenceError is thrown
DIt prints object
Correct Answer: Option C
typeof returns "undefined" only for names that are not declared at all. token is declared (hoisted) but in its TDZ, so even typeof throws.
Why does for (let i = 0; i < 3; i++) setTimeout(() => console.log(i)); print 0, 1, 2?
AEach iteration gets a new binding of i, which its callback captures
BsetTimeout copies the value of i when it is called
Clet variables are read-only inside loops
DThe loop waits for each timer before continuing
Correct Answer: Option A
A let in the loop head is re-created for every iteration (with the previous value copied in). Each arrow function closes over its own i. With var there is one i, so all callbacks print 3.
Why does for (const i = 0; i < 3; i++) { … } fail, while for (const x of list) { … } works?
Aconst cannot be declared inside parentheses
Bfor…of converts const to let automatically
CBoth fail in strict mode only
Di++ tries to reassign the constant i; for…of creates a fresh x for each iteration instead of changing it
Correct Answer: Option D
The first iteration runs, then i++ throws TypeError: Assignment to constant variable. for…of and for…in bind a new const per iteration and never reassign it.
What happens with let mode = "light"; { var mode = "dark"; } in the same scope?
ASyntaxError: the var is hoisted to the outer scope, where mode is already declared with let
BThe block gets its own mode, and the outer one stays "light"
Cmode becomes "dark" everywhere
DIt works only in strict mode
Correct Answer: Option A
A var ignores the block and belongs to the enclosing function/global scope – the same scope as the let – so it is a redeclaration: Identifier 'mode' has already been declared. A let inside the block would shadow correctly.
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·