Variables: const, let, var
A binding is a name that points at a value. JavaScript has three ways to create one, and they differ in two things only: whether the name may point at another value later, and where the name exists. const forbids a second assignment, let allows it, and var is the form the language had before either existed.
The rule that decides which one to write is short. Use const for every binding that does not need to change, let for the few that do, and var never in new code. This lesson shows what each one does with a program, and why a var in an old file behaves in ways that let was designed to stop.
const
const creates a binding that may not be assigned again. It does not make the value immutable: an object behind a const keeps its properties and may change them, and an array keeps its elements. What the keyword fixes is the pointer from the name to the value.
To freeze the value as well, pass the object to Object.freeze. The program below writes to a frozen property inside a try block, because the write throws a TypeError in strict mode. The file declares "use strict" at the top, which a module would do by itself.
'use strict';
const config = Object.freeze({ debug: false });
try {
config.debug = true;
} catch (error) {
console.log(error.name + ': ' + error.message);
}
console.log('debug:', config.debug);
node frozen.js
TypeError: Cannot assign to read only property 'debug' of object '#<Object>'
debug: false
The message is the one the runtime threw, caught and printed. With the try block gone, the same write ends the program with the same message and a non-zero status. Without strict mode the write is silently ignored, which is worse: the program continues with a value that does not match what the source says.
let and block scope
let creates a binding that may be assigned again, and the binding lives in the block where it was declared: the braces of an if, a loop or a bare pair. Outside those braces the name does not exist. The program below declares one name of each kind inside an if block and reads both after it.
let counter = 0;
counter += 1;
console.log('let counter:', counter);
if (counter > 0) {
var leaked = 'var escapes the block';
let kept = 'let stays inside the block';
console.log('inside:', kept);
}
console.log('outside:', leaked);
console.log('typeof kept outside:', typeof kept);
node scope.js
let counter: 1
inside: let stays inside the block
outside: var escapes the block
typeof kept outside: undefined
var escaped the block and let did not, and typeof reports the missing name as "undefined" rather than throwing. That difference is the whole reason let exists: a loop counter declared with let belongs to one pass of the loop, while a var counter is one binding shared by every pass.
var and hoisting
var is function-scoped, and the declaration is hoisted to the top of its function before the code runs. The name exists from the first line, with the value undefined, and the assignment happens where it is written. Reading a var before its assignment is therefore not an error; it prints undefined.
console.log('before:', value);
var value = 5;
console.log('after:', value);
node varhoist.js
before: undefined
after: 5
That output is the classic source of a bug: the first line looks like a value that was never set, and the cause is a declaration further down. A function declared with function is hoisted with its body, which the lesson on functions uses; a var is hoisted only as a name.
The temporal dead zone
A let or const binding is hoisted too, but it is not initialised until its declaration runs. Between the start of the block and that line the name exists and may not be read: the region is called the temporal dead zone, and a read there throws a ReferenceError instead of returning undefined.
try {
console.log('before:', count);
} catch (error) {
console.log(error.name + ': ' + error.message);
}
let count = 1;
console.log('after:', count);
node tdz.js
ReferenceError: Cannot access 'count' before initialization
after: 1
The error was caught, printed and the program continued, which is why the second line appears as well. The message names the binding and the reason, and the same message is what an uncaught error would print as its second line. The dead zone is a feature: a mistake that a var would hide becomes a loud failure at the line that made it.
Exercises
- Remove Object.freeze from frozen.js and run it again. Does the write still throw, and what does the second line print?
- Move the let kept declaration out of the if block in scope.js. Which two lines of the output change?
- Declare let value = 1; instead of var value = 5; in varhoist.js and run it. What replaces undefined on the first line?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
constfix about a binding?Answer
That the name may not be assigned another value
const fixes the pointer, not the value: an object behind it may still change, which is what Object.freeze prevents.
-
Where does a
letbinding exist?Answer
In the block where it is declared
let is block-scoped, so the braces of an if or a loop end the name.
-
What does the last line of this program print?
const flag = true; if (flag) { var leaked = "var"; let kept = "let"; console.log(kept); } console.log(typeof leaked, typeof kept);Answer
string undefined
var escapes the block as a name, and typeof answers undefined for the name that let kept inside.
-
What does a hoisted
varhold before its assignment runs?Answer
undefined
Only the name is hoisted; the value is assigned at the line where the assignment is written.
-
What does the first line of this program print?
console.log(value); var value = 5; console.log(value);Answer
undefined
The declaration is hoisted and not initialised, so the read finds undefined.
-
What happens when a
letbinding is read before its declaration runs?Answer
It throws a ReferenceError
The name is in the temporal dead zone, and a read there throws the same error whether or not a value follows.
-
Which keyword does this course use for a binding that never changes?
Answer
const
const states the intent, and var is kept out of new code because of function scope and hoisting.
-
What does this program print?
const config = { debug: false }; config.debug = true; console.log(config.debug);Answer
true
const protects the binding, and the property of the object behind it may still be assigned.
-
Which error does a write to a frozen property throw in strict mode?
Answer
TypeError
The property is read only, and the runtime reports a TypeError with the property name in the message.
-
Why does a loop counter behave differently with
letand withvar?Answer
A let counter belongs to one pass of the loop, and a var counter is shared by all of them
let creates a new binding for each pass, which is what a callback created inside the loop needs.
The code on this page was run with Node.js 24.22.1 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev