Declaring variables
Overview
A variable is a name for a value. Instead of writing the same value again and again, you give it a name once and use the name everywhere. If the value changes, you only update it in one place — and the name tells readers what the value means.
JavaScript gives you three ways to declare a variable: const, let and the older var.
const course = 'JavaScript Essentials';
let lessonsDone = 3;
lessonsDone = lessonsDone + 1;
console.log(lessonsDone); // 4Declaring, assigning and reading
Working with a variable involves three steps, which you’ll often do in one line:
let score; // 1. declare: create the name (its value is undefined)
score = 10; // 2. assign: store a value in it
console.log(score); // 3. read: use the value → 10
let lives = 3; // declare and assign together (most common)You can declare several variables in one statement, separated by commas, but one per line is easier to read:
let x = 0, y = 0; // allowed
let width = 100; // clearer
let height = 50;const and let
Use const when the name will always point to the same value. Use let when you need to reassign it later.
It helps to think of a variable as a label attached to a value, rather than a box that contains it. const glues the label to one value for good; let lets you move the label to a different value.
const max = 10;
max = 11; // TypeError: Assignment to constant variable.
let visits = 0;
visits = visits + 1; // fine
visits += 1; // the same thing, shorterA const must be given its value immediately, because it can never be assigned later:
const answer; // SyntaxError: Missing initializer in const declaration
constdoesn’t freeze objects. You can’t point aconstat a new object, but you can still change the object’s properties or push items into an array. To truly lock an object, useObject.freeze()— covered in Equality and immutability.
const user = { name: 'Asha' };
user.name = 'Ravi'; // allowed — the object changed, not the label
user = { name: 'Mina' }; // TypeError — that would move the label
const tags = ['js'];
tags.push('web'); // allowedWhich one should I use?
Start every variable as const. If you later find you need to reassign it, change it to let. In practice most variables in good code are const, and when you see a let, it’s a useful signal: this value is going to change, keep an eye on it.
Naming variables
Variable names can contain letters, digits, _ and $, but cannot start with a digit, and cannot be reserved words such as let, class or return.
let userName; // ✓ camelCase — the JavaScript convention
let _private; // ✓
let $element; // ✓
let 2ndPlace; // ✗ starts with a digit
let user-name; // ✗ dash means minus
let class; // ✗ reserved wordGood names make code read like a sentence:
| Instead of | Prefer | Why |
|---|---|---|
d |
daysUntilDue |
Says what it holds |
data |
orders |
Specific |
flag |
isLoggedIn |
Booleans read well with is, has, can |
arr |
selectedIds |
Plural names for lists |
By convention, values that are fixed for the whole program — configuration, magic numbers — are sometimes written in UPPER_SNAKE_CASE: const MAX_UPLOAD_MB = 10;.
Block scope
let and const only exist inside the block where they were declared — the nearest pair of curly braces. This area is called the variable’s scope.
if (true) {
const message = 'inside';
console.log(message); // 'inside'
}
console.log(message); // ReferenceError: message is not definedInner blocks can see variables from outer blocks, but not the other way round. Two separate blocks can each have their own variable with the same name, without clashing:
for (let i = 0; i < 2; i++) { /* this i … */ }
for (let i = 0; i < 2; i++) { /* … and this i are different */ }The temporal dead zone
A let or const exists from the start of its block, but you can’t use it until the line that declares it has run. Using it too early throws an error. That stretch of code is nicknamed the temporal dead zone:
console.log(price); // ReferenceError: Cannot access 'price' before initialization
const price = 9.99;This is a good thing — it turns a likely bug into a clear error. You’ll learn more in Scope and hoisting.
Why not var?
var is how variables were declared before 2015. It has two behaviours that make bugs easy to write:
- It ignores blocks. A
varis scoped to the whole function (or the whole script), so it “leaks” out ofifblocks and loops. - It is hoisted with the value
undefined. You can read it before it’s declared and getundefinedinstead of an error.
if (true) {
var leaked = 'oops';
}
console.log(leaked); // 'oops' — visible outside the block
console.log(early); // undefined — no error, just a silent bug
var early = 5;var also lets you declare the same name twice without complaint, so you can accidentally overwrite a variable. Modern code uses let and const instead. You’ll still see var in older tutorials and libraries, so it’s worth recognising.
const |
let |
var |
|
|---|---|---|---|
| Can reassign | No | Yes | Yes |
| Scope | Block | Block | Function |
| Use before declaration | Error | Error | undefined |
| Redeclare in same scope | Error | Error | Allowed |
| Use in new code | ✓ default | ✓ when needed | ✗ |
Undeclared variables
If you assign to a name you never declared, older non-strict code silently creates a global variable. That’s almost always a typo:
let counter = 0;
countr = 1; // creates a global "countr" in sloppy mode; ReferenceError in strict modeStrict mode and modules turn this into an error, which is one more reason to use them.
Pick the right keyword
Rewrite this so that values which never change use const, and give the vague variable a descriptive name.
let siteName = 'Academy';
let visits = 0;
let x = 20;
visits = visits + 1;
console.log(`${siteName}: ${visits} of ${x} visits`);const siteName = 'Academy';
const maxVisits = 20;
let visits = 0;
visits = visits + 1;
console.log(`${siteName}: ${visits} of ${maxVisits} visits`);Summary
- Use
constby default andletwhen the value must change. conststops reassignment, not changes inside an object or array.- Both are block-scoped — they only exist inside the nearest
{ }. - Using a
let/constbefore its declaration throws (the temporal dead zone). - Avoid
varin new code; it is function-scoped and hoisted.