Declaring Variables in JavaScript: let, const and Naming
How to declare variables the modern way: let vs const and when to use each, initialization, why const objects can change, loop variables, redeclaration and shadowing errors, naming conventions that professional codebases follow, and the mistakes beginners make most.
kvi5hnuCode Sprout team member6 min readOn this page
A variable is a name bound to a value, so you can refer to the value later. In modern JavaScript you create variables with two keywords: let for names whose value will change, and const for names that will always refer to the same value. A third keyword, var, is the pre-2015 way; it has unusual rules, covered in article 26.
let: a variable you can reassign
let score; // declared, not yet assigned
console.log(score); // undefined until you assign it
score = 10;
score = score + 5; // reassign as often as you like
console.log(score);
let lives = 3, level = 1; // several in one statement
let bonus = level * 100; // initializers can use earlier variables
console.log(lives, level, bonus);
undefined
15
3 1 100
A let variable without an initializer starts as undefined. Assigning an initial value when you declare is good practice: it documents what the variable is for and avoids accidental undefineds.
const: a binding that can't be reassigned
const works like let, with two differences: you must initialize it, and you can't assign to it again.
const MAX_USERS = 50;
console.log(MAX_USERS);
try {
eval("const unset;"); // a const needs a value right away
} catch (err) {
console.log(err.name);
}
try {
const limit = 10;
limit = 20; // reassignment is an error at run time
} catch (err) {
console.log(err.name);
}
50
SyntaxError
TypeError
(The eval wraps code that wouldn't even compile, so the rest of the example can run. In normal code, const unset; makes the whole file fail to load.)
const means "constant binding", not "constant value"
const freezes the name, not the value. If the value is an object or array, its contents can still change:

const cart = [];
cart.push("apple"); // fine: the array changes, the binding doesn't
cart.push("pear");
console.log(cart);
const user = { name: "Ana" };
user.name = "Bea"; // fine
console.log(user);
[ 'apple', 'pear' ]
{ name: 'Bea' }
To make the object itself unchangeable, use Object.freeze (article 21). Primitive values are immutable anyway, so a const holding a number or string is fully constant.
let or const?
There are two schools of thought:
- const by default (the most common style today, used by Airbnb's and Google's style guides and enforced by ESLint's
prefer-const): declare everything withconst, and switch toletonly when you actually reassign. Readers then know that anyletwill change, and accidental reassignment becomes an error. - const for true constants: use
constonly for values that are conceptually fixed (configuration, physical constants) andletfor everything else.
This course uses const by default. In practice most variables never get reassigned, especially in code built from small functions and array methods like map and filter. Remember that const says nothing about mutability: a const array can still be pushed to.
Variables in loops
Loops are a common place for let:
const temps = [18, 21, 25];
for (let i = 0; i < temps.length; i++) { // i changes, so let
console.log(i, temps[i]);
}
for (const t of temps) { // a fresh t each iteration, so const works
console.log(t);
}
for (const key in { a: 1, b: 2 }) {
console.log(key);
}
0 18
1 21
2 25
18
21
25
a
b
const works in for...of and for...in because each iteration creates a new binding. It doesn't work as the counter of a classic for (;;) loop, because i++ reassigns it: for (const i = 0; i < 3; i++) throws a TypeError after the first iteration.
Each iteration of a for loop with let also gets a fresh copy of i, which matters when functions created in the loop remember it (closures, part 8). Article 26 shows the classic bug that var causes here.
Redeclaring and shadowing
Within one scope, a name can be declared only once with let or const:
try {
eval("let total = 1; let total = 2;");
} catch (err) {
console.log(err.name);
}
try {
eval("var count = 1; let count = 2;"); // mixing with var doesn't help
} catch (err) {
console.log(err.name);
}
SyntaxError
SyntaxError
This rule catches real bugs, such as pasting a block of code that declares a name you already used.
You can declare the same name in a nested block. The inner declaration shadows the outer one inside that block:
const label = "outer";
if (true) {
const label = "inner"; // a different variable that hides the outer one
console.log(label);
}
console.log(label);
inner
outer
Shadowing is legal but often confusing, especially when the inner block also needs the outer value. ESLint's no-shadow rule can flag it. Block scope is covered in depth in article 27.
Naming variables
Identifiers follow the rules from article 6: letters, digits, _ and $, not starting with a digit, and not a reserved word. Beyond the rules, these conventions are near-universal in JavaScript:
| Kind of name | Convention | Examples |
|---|---|---|
| variables, functions, methods | camelCase | userName, totalPrice, getUser |
| classes and constructors | PascalCase | ShoppingCart, HttpClient |
| fixed, module-level constants | UPPER_SNAKE_CASE (optional) | MAX_RETRIES, API_URL |
| booleans | an is/has/can/should prefix | isLoggedIn, hasItems, canEdit |
| "private by convention" (old style) | leading _ | _cache (prefer #private in classes) |
Good names are specific (invoiceTotal rather than data or x), pronounceable, and as long as needed and no longer. Loop counters (i, j) and short-lived arrow parameters (n => n * 2) are fine as single letters.
Note that UPPER_SNAKE_CASE is for values that are constant by meaning, like a retry limit, not for every const: const user = await getUser() stays camelCase.
Common mistakes
const attempts = [
"let let = 1;", // let isn't allowed as a let/const name
"let w = w + 1;", // using a variable in its own initializer
"const n = 1; n++;", // ++ is an assignment
"const [a, b] = [1, 2]; a = 3;", // destructured consts are consts too
];
for (const code of attempts) {
try {
eval(code);
} catch (err) {
console.log(code.padEnd(32), err.name);
}
}
let let = 1; SyntaxError
let w = w + 1; ReferenceError
const n = 1; n++; TypeError
const [a, b] = [1, 2]; a = 3; TypeError
And one the engine doesn't catch in sloppy mode: forgetting the keyword entirely. totl = 5 without let or const silently creates a global variable (article 20). Strict mode and modules turn it into a ReferenceError.
Common questions
Is const faster than let?
Not in any way you'd measure. Engines analyze both. Choose based on meaning: const documents that the binding doesn't change.
Can I declare a variable without let, const or var?
In sloppy-mode scripts, assigning to an undeclared name creates a global property, which is almost always a bug. In strict mode and in modules it throws a ReferenceError. Always declare.
Do JavaScript variables have types?
No. A variable can hold any type of value and switch types later. TypeScript adds type annotations (let count: number = 0) that are checked before the code runs and erased afterward.
Why does my const array allow push but not arr = []?
push changes the array object, which const doesn't prevent. arr = [] changes which object the name refers to, which is exactly what const forbids. To empty a const array in place, use arr.length = 0.
Summary
letdeclares a reassignable variable (initiallyundefinedif not initialized);constdeclares a binding that must be initialized and can't be reassigned.constdoesn't make objects immutable; their contents can change.- Use
constby default andletwhen you reassign; avoidvar. for...of/for...incan useconst; a classicfor (;;)counter needslet.- Duplicate
let/constdeclarations in one scope are aSyntaxError; nested blocks can shadow names. - Name variables in
camelCase, classes inPascalCase, true constants inUPPER_SNAKE_CASE, booleans withis/has.
Practice Questions
What's printed?
let x;
console.log(x);
x = 5;
console.log(x);
Answer
undefined then 5.
Does this code throw?
const settings = { dark: false };
settings.dark = true;
Answer
No. The object's property changes; the binding settings still refers to the same object.
Which of these loops is valid: snippet A or snippet B?
for (const i = 0; i < 3; i++) {}
for (const n of [1, 2, 3]) {}
Answer
The second. The first throws a TypeError when i++ tries to reassign the constant.
Why is snippet A an error, but snippet B isn't?
let total = 1;
let total = 2;
let total = 1;
{ let total = 2; }
Answer
The first declares the same name twice in one scope. The second declares a new variable in a nested block, which shadows the outer one.
Name these by convention: a boolean that says whether a modal is open; a class for a shopping cart; the maximum number of uploads allowed.
Answer
isModalOpen, ShoppingCart and MAX_UPLOADS (or maxUploads; constant-case is optional).
Previous: Object-to-Primitive Conversion in JavaScript: valueOf, toString and Symbol.toPrimitive
Next: var and Hoisting in JavaScript: Function Scope and Why let Replaced It

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.