Variables, Scope and Hoisting
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Distinguish function scope from block scope.
- Explain hoisting and the temporal dead zone.
- Choose between var, let and const deliberately.
Overview
#Scope is where a name lives
A scope is the region of a program where a name is visible. JavaScript uses lexical scope: the position of a declaration in the source code decides which scopes can see it, not the order in which functions run. There are global scopes, module scopes, function scopes and block scopes.
var, let and const
var is function-scoped and hoisted with an initial value of undefined. let and const are block-scoped: they exist only inside the nearest pair of braces. const prevents reassignment of the binding, though it does not make an object immutable. Prefer const by default, use let when a binding must change, and avoid var in new code.
Hoisting
Declarations are processed before code runs. Function declarations are hoisted together with their bodies, so you can call them earlier in the file. var declarations are hoisted but initialized to undefined. let and const are hoisted too, but they stay uninitialized until execution reaches the declaration. The gap between the start of the block and the declaration is the temporal dead zone, and reading the binding there throws a ReferenceError.
console.log(typeof hoisted); // "function"
function hoisted() {}
console.log(value); // undefined
var value = 5;
console.log(blocked); // ReferenceError: Cannot access before initialization
let blocked = 5;
Why block scope matters
Block scope keeps helper variables from leaking into the rest of a function. A loop counter declared with let exists only inside the loop, and a for loop with let creates a fresh binding for each iteration, which is exactly what closures need.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this print?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptconsole.log(value); var value = 7; console.log(value);Exercise 2Explain
Explain why reading a let binding before its declaration throws a ReferenceError.
starter.javascriptconsole.log(count); let count = 1;Reveal the reference answer
reference.javascriptlet declarations are hoisted, so the name count exists for the whole block. Unlike var, the binding is not initialized to undefined. It stays uninitialized until execution reaches the declaration line. Reading it before that point is in the temporal dead zone and throws a ReferenceError.Authored expected output: ReferenceError
The temporal dead zone is the interval between entering a block and reaching the declaration. It exists to catch use-before-initialization mistakes.
Exercise 3Implement
Implement `sumInBlock(numbers)` that sums an array using a loop counter declared with let, so the counter does not leak outside the loop. Running `console.log(sumInBlock([1, 2, 3])); console.log(typeof i);` should print `6` then `undefined`.
starter.javascriptfunction sumInBlock(numbers) { // your code here }Reveal the reference answer
reference.javascriptfunction sumInBlock(numbers) { let total = 0; for (let i = 0; i < numbers.length; i++) { total += numbers[i]; } return total; }Authored expected output: 6 undefined
Because i is declared with let inside the for header, it is scoped to the loop block. Referencing i after the loop is a ReferenceError at runtime only if the name is not declared elsewhere; typeof reports "undefined" when the name is entirely absent.
Exercise 4Debug
This loop logs the same value three times instead of 0, 1, 2. Fix it without removing the closure.
starter.javascriptfor (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }Reveal the reference answer
reference.javascriptfor (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }Authored expected output: 0 1 2
var creates one function-scoped binding shared by every callback, so all three read the final value 3. A let declaration in a for loop creates a fresh binding per iteration, so each callback closes over its own value.
Exercise 5Test
Write a test that proves reassigning a const binding throws a TypeError.
starter.javascriptfunction expectThrows(fn, label) { try { fn(); } catch (error) { console.log(label + ': ' + error.constructor.name); return; } throw new Error(label + ': expected a throw'); }Reveal the reference answer
reference.javascriptconst config = { retries: 3 }; expectThrows(() => { config = {}; }, 'reassign const'); config.retries = 5; console.log('mutation allowed: ' + config.retries);Authored expected output: reassign const: TypeError mutation allowed: 5
const protects the binding, not the object. Reassigning the binding throws a TypeError, but mutating a property of the referenced object succeeds.
Exercise 6Interview
Explain hoisting and the temporal dead zone to an interviewer, then state one practical rule you follow.
starter.javascriptgreet(); function greet() { return 'hi'; }Reveal the reference answer
reference.javascriptHoisting is the process of registering declarations before code executes. Function declarations are usable before their line. var is initialized to undefined. let and const are registered but uninitialized, and reading them before the declaration is in the temporal dead zone and throws. The practical rule is to declare every binding at the top of its scope and prefer const.Authored expected output: hi
Calling greet before its declaration works because the function declaration is fully hoisted. The answer should separate function hoisting from var initialization and from the temporal dead zone.
Common misconceptions
#- let and const are not hoisted at all.
- const makes the value frozen and deeply immutable.
- var and let differ only in whether reassignment is allowed.
Follow-up practice
#- javascript-foundations-functions-and-closures
- javascript-foundations-objects-and-prototypes
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.