Sub topic 1
Three Ways to Declare a Variable
JavaScript has three keywords for creating variables: var, let, and const. They look almost the same on the page, but they behave differently in ways that cause real bugs. This chapter covers the basics: the syntax of each keyword, what happens when a variable is created, and the terms the rest of the tutorial uses. Later chapters cover scope, hoisting, and the other differences in detail.
Prerequisites
This chapter assumes you already know:
- Basic JavaScript syntax: statements, expressions, and operators such as
=,+, and===. - How to write and call functions.
- How
ifstatements andforloops work. - How to run code and read output with
console.log, in either a browser console or Node.js. - The basics of objects and arrays, such as
{ a: 1 }and[1, 2, 3].
Every example runs as-is in Node.js 16 or later, or in the console of any current browser. Save an example to a file such as demo.js and run node demo.js, or paste it into a console.
The Three Keywords at a Glance
Here is each keyword in its simplest form:
let count = 0; // can be reassigned later
const limit = 10; // must be initialized; cannot be reassigned
var legacy = 'old'; // older function-scoped declaration
count = count + 1;
console.log(count, limit, legacy); // 1 10 'old'Each line is a variable declaration. It does two things:
- It creates a name (
count,limit,legacy) in the current scope. - It gives that name a starting value. This step is optional for
letandvarand required forconst.
The line count = count + 1; is not a declaration. It is an assignment, which stores a new value in a variable that already exists.
Where each keyword came from
var has been in JavaScript since 1995. let and const came with ECMAScript 2015 (ES6), mainly to fix problems with var. All three still work in every modern engine, and var will not be removed because that would break old websites. Modern code mostly uses const and let, but you will still see var in older codebases, tutorials, and some generated code, so you need to understand all three.
Declaration, Initialization, and Assignment
These three terms come up in every chapter, and many bugs come from mixing them up.
- Declaration introduces a name:
let total. - Initialization gives the variable its first value: the
= 0inlet total = 0. - Assignment replaces the value of a variable that already exists:
total = 5.
A binding is the link between a name and the place its value is stored. When this tutorial says "const creates a binding that cannot be reassigned," it means you cannot point the name limit at a different value. This is a different claim from "the value cannot change," and the chapter on const covers why that matters.
Declaring Without a Value
let and var can be declared without an initializer. The variable then holds undefined until you assign something.
let pending;
var oldStyle;
console.log(pending); // undefined
console.log(oldStyle); // undefined
pending = 'ready';
console.log(pending); // 'ready'This is useful when the value depends on a condition:
const score = 72;
let grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 70) {
grade = 'B';
} else {
grade = 'C';
}
console.log(grade); // 'B'const does not allow this. A const declaration must include an initializer, and leaving it out is a SyntaxError. A syntax error stops the whole script before any of it runs, so the example below compiles the bad code separately with new Function to show the error without crashing the file:
try {
new Function('const limit;');
} catch (e) {
console.log(e.name); // 'SyntaxError'
console.log(e.message); // e.g. 'Missing initializer in const declaration'
}Declaring Several Variables at Once
One statement can declare several variables, separated by commas. The keyword applies to every name in the list.
let x = 1, y = 2, z;
const width = 800, height = 600;
console.log(x, y, z); // 1 2 undefined
console.log(width * height); // 480000This saves a few characters, but it makes code harder to scan and produces noisier diffs when one variable changes. Most style guides, and the ESLint rule one-var in many configurations, prefer one declaration per line:
let x = 1;
let y = 2;
let z;
console.log(x, y, z); // 1 2 undefinedDeclaring Variables with Destructuring
All three keywords work with destructuring, a syntax that pulls values out of an object or array and assigns them to new variables in one declaration.
const user = { name: 'Ada', role: 'admin', active: true };
const { name, role } = user;
console.log(name, role); // 'Ada' 'admin'
const point = [3, 4];
let [px, py] = point;
px = px * 2;
console.log(px, py); // 6 4
// Rename and provide a default value
const { active: isActive, team = 'none' } = user;
console.log(isActive, team); // true 'none'The keyword applies to every variable the pattern creates. With const { name, role } = user;, neither name nor role can be reassigned. If you need just one of them to be reassignable, use two declarations.
Naming Rules
The same naming rules apply to all three keywords. A variable name (an identifier):
- must start with a letter,
_, or$; - may contain letters, digits,
_, and$after the first character; - is case-sensitive, so
totalandTotalare different variables; - cannot be a reserved word such as
class,return,const, orfunction.
let userName = 'ada';
let _private = 1;
let $element = null;
let item2 = 'second';
let café = 'unicode letters are allowed';
console.log(userName, _private, $element, item2, café);
// let 2item = 'x'; // SyntaxError: cannot start with a digit
// let class = 'x'; // SyntaxError: reserved wordThe usual convention is camelCase for variables and functions. Many teams use UPPER_SNAKE_CASE for true constants that are fixed configuration values, such as const MAX_RETRIES = 3;. Not every const gets uppercase names, though. Most const variables are just values that happen never to be reassigned, and they use camelCase.
Declarations in Loops
You will often see declarations in loop headers. The keyword you choose here matters:
// Classic for loop: the counter changes, so use let
for (let i = 0; i < 3; i++) {
console.log('index', i);
}
// for...of: each pass gets a fresh variable, so const works
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log('color', color);
}
// for...in over object keys: const works here too
const settings = { theme: 'dark', lang: 'en' };
for (const key in settings) {
console.log(key, settings[key]);
}A classic for loop with const fails because i++ tries to reassign the counter:
try {
for (const i = 0; i < 3; i++) {
console.log(i); // prints 0 once
}
} catch (e) {
console.log(e.name); // 'TypeError' (raised by i++)
}The loop body runs once, prints 0, and then the i++ step throws. Why for...of creates a fresh variable on each pass, and why that matters for functions created inside loops, is covered in the chapter on loops and closures.
A Preview of the Differences
The keywords differ along several dimensions. The table below lists them so you know what to expect. Each row has its own chapter later in this tutorial, so treat it as a map rather than something to memorize now.
| Behavior | `var` | `let` | `const` |
|---|---|---|---|
| Scope | Function | Block | Block |
| Initializer required | No | No | Yes |
| Reassignment allowed | Yes | Yes | No (`TypeError`) |
| Redeclaration in same scope | Allowed | `SyntaxError` | `SyntaxError` |
| Access before declaration | `undefined` | `ReferenceError` | `ReferenceError` |
| Top-level creates `globalThis` property (classic scripts) | Yes | No | No |
Most of the surprising behavior in the var column is why let and const were added.
Common Errors at This Stage
These errors show up most often when people are first working with declarations:
| Mistake | What happens | Fix |
|---|---|---|
| `const x;` | `SyntaxError`: missing initializer | Give it a value, or use `let` |
| `const n = 1; n = 2;` | `TypeError`: assignment to constant variable | Use `let` if the value must change |
| Using a name that was never declared, e.g. `console.log(missing)` | `ReferenceError`: missing is not defined | Declare it first, and check spelling and case |
| `let a = b = 5;` | `b` becomes an accidental global, or throws in strict mode | Declare each variable separately |
| `for (const i = 0; i < n; i++)` | `TypeError` after the first iteration | Use `let` for counters |
Note which errors are SyntaxErrors and which are runtime errors. A SyntaxError stops the whole script before any line runs, so even code above the mistake never executes. A TypeError or ReferenceError happens when the bad line runs, so everything before it has already executed. When a script prints nothing at all, check for a syntax error first.
Exercise
What does this code print, and why? let a; var b; const c = a; console.log(a, b, c);
Show answer
It prints undefined undefined undefined. let a and var b are declared without initializers, so both hold undefined. const c = a is legal because it has an initializer; the initial value is the current value of a, which is undefined. A const must be initialized, but the value it is initialized with can be undefined.
Exercise
Rewrite this so label is declared with const: let label; if (count === 1) { label = 'item'; } else { label = 'items'; }
Show answer
Use a ternary expression so the value exists at the moment of declaration: const label = count === 1 ? 'item' : 'items';. A const needs its value in the declaration itself, so the branching has to happen inside an expression rather than in separate assignment statements.
Exercise
A teammate writes for (const i = 0; i < items.length; i++) { process(items[i]); }. It processes the first item and then throws. Name the error and give two correct rewrites.
Show answer
It throws a TypeError because i++ tries to reassign a const binding. One fix is to change the declaration to let: for (let i = 0; i < items.length; i++) { ... }. If you don't need the index, a cleaner fix is for (const item of items) { process(item); }, which works with const because each iteration gets a new binding.
Exercise
In const { id, tags = [] } = record;, what are the values of id and tags if record is { id: 7 }, and can you later write tags = ['new'];?
Show answer
id is 7 and tags is [], because the default applies when the property is missing (undefined). You cannot write tags = ['new'];: const applies to every variable in the destructuring pattern, so that assignment throws a TypeError.