Variables
A variable is a named container for a value. You create one, put something in it, and refer to it by name later. JavaScript has three keywords for declaring variables — let, const and the older var — and choosing between them is simpler than it first looks.
let and const
let score = 0; const playerName = "Riya"; score = score + 10; console.log(playerName, "has", score, "points");
Riya has 10 points
letdeclares a variable whose value can be reassigned later.constdeclares a variable that can't be reassigned after it's created.
const maxPlayers = 4;
maxPlayers = 5;
Uncaught TypeError: Assignment to constant variable.
Rule of thumb: use const by default, and switch to let only when you know the value must change (a counter, a running total). Code full of const is easier to read, because you know those names always mean the same thing.
Declaring without a value
A let can be declared first and assigned later. Until then, its value is undefined. A const must be given a value immediately:
let message; console.log(message); message = "Ready"; console.log(message);
undefined Ready
const doesn't freeze objects
const stops you assigning a new value to the name. It doesn't stop the contents of an object or array from changing:
const cart = ["apple"]; cart.push("pear"); console.log(cart); const user = { name: "Lee" }; user.name = "Lia"; console.log(user);
[ 'apple', 'pear' ]
{ name: 'Lia' }cart still points to the same array — it's the array that changed. Writing cart = [] would be the error.
Block scope
let and const exist only inside the { } block where they're declared:
if (true) { const secret = 42; console.log("inside:", secret); } console.log("outside:", secret);
inside: 42 Uncaught ReferenceError: secret is not defined
This keeps variables close to where they're used and prevents accidental clashes. Lesson 25 covers scope in detail.
Why not var?
var is how variables were declared before 2015, and you'll see it in older code. It behaves differently in ways that cause bugs:
var | let / const | |
|---|---|---|
| Scope | Whole function — ignores blocks | The enclosing block |
| Use before declaration | Allowed, gives undefined | Error |
| Redeclare the same name | Allowed silently | Error |
for (var i = 0; i < 3; i++) {} console.log("var i after the loop:", i);
var i after the loop: 3
The loop counter "leaks" out of the loop. With let i, the last line would be an error instead — which is what you want. There's no reason to use var in new code.
Several at once
You can declare multiple variables in one statement, separated by commas, though one per line is usually clearer:
let x = 1, y = 2, z = 3;
console.log(x + y + z);
6
Naming well
- Use descriptive camelCase names:
totalPrice, nottporx. - Booleans read well as questions:
isLoggedIn,hasError. - Names can't start with a digit or be reserved words;
2ndPlaceandclassare invalid.