Variables
Most of the time, a program’s whole job is to shuffle information around. A shop tracks products and a cart; a chat app tracks people and their messages. That information has to live somewhere between the moment you receive it and the moment you use it — and that somewhere is a variable.
Two quick examples of the kind of data an app juggles:
- An online shop — the goods being sold and the items in a shopping cart.
- A chat application — the users, their messages, and much more.
Variables are how we hold onto all of it.
A variable
A variable is a named storage for data. Think of it as a labelled container: you put a value in, stick a name on the outside, and from then on you refer to the value by its name instead of repeating the value everywhere.
In JavaScript you create one with the let keyword. The statement below declares (creates) a variable named message:
let message;
Right now the box exists but is empty. We put data in with the assignment operator =:
let message;
message = 'Hello'; // store the string 'Hello' in the variable named message
The string is now parked in the memory that belongs to message, and we read it back just by naming the variable:
let message;
message = 'Hello!';
alert(message); // shows the variable content
Declaring and assigning on separate lines is useful when you’re explaining a concept, but in real code you usually do both at once:
let message = 'Hello!'; // define the variable and assign the value
alert(message); // Hello!
Watch it happen
Declaring, assigning, and reassigning are the three moves you’ll make thousands of times. Step through them below and watch the box named message fill, then get overwritten:
Notice the key idea in step 3: a variable holds one value at a time. Assign a new one and the old one is simply gone.
We can also declare several variables in one line:
let user = 'Maya', age = 25, message = 'Hello';
That looks shorter, but it reads worse — so don’t. One variable per line is easier to scan and to edit later:
let user = 'Maya';
let age = 25;
let message = 'Hello';
Some people prefer a multiline version of the one-statement style:
let user = 'Maya',
age = 25,
message = 'Hello';
…or even the “comma-first” style:
let user = 'Maya'
, age = 25
, message = 'Hello';
Technically all of these do exactly the same thing. Which you use is a matter of taste — pick the one your team finds readable and move on.
A real-life analogy
The mental model that makes variables click: picture a box with a labelled sticker. The sticker is the name; whatever’s inside is the value.
message is a box labelled 'message' holding the value 'Hello!'.You can put any value in the box, and you can swap it out as many times as you like:
let message;
message = 'Hello!';
message = 'World!'; // value changed
alert(message);
When you assign a new value, the old one is evicted — there’s only ever room for one. After the line above runs, the box named message holds 'World!', and 'Hello!' is nowhere to be found:
We can also declare two variables and copy the data from one into the other:
let hello = 'Hello world!';
let message;
// copy 'Hello world' from hello into message
message = hello;
// now two variables hold the same data
alert(hello); // Hello world!
alert(message); // Hello world!
After the copy, both boxes hold their own equal copy of the string — two independent stickers, same contents:
message = hello copies the value across; each variable now holds its own copy.Variable naming
There are just two hard rules for variable names in JavaScript:
- The name may contain only letters, digits, and the symbols
$and_. - The first character must not be a digit.
Valid names:
let userName;
let test123;
When a name spans several words, the convention is camelCase: run the words together, capitalising every word after the first — myVeryLongName.
Curiously, $ and _ are ordinary name characters too, with no special meaning — you can build names out of them alone:
let $ = 1; // declared a variable with the name "$"
let _ = 2; // and now a variable with the name "_"
alert($ + _); // 3
Names that break the rules:
let 1a; // cannot start with a digit
let my-name; // hyphens '-' aren't allowed in the name
Constants
To declare a variable whose value must never change, use const instead of let:
const releaseDate = '11.05.2016';
These are called constants. Try to reassign one and JavaScript stops you:
const releaseDate = '11.05.2016';
releaseDate = '20.07.2018'; // error, can't reassign the constant!
const is as much a message to humans as to the engine: when you know a value will never change, declaring it const guarantees it and tells every future reader “don’t worry, this stays put.” A good default is to reach for const first and switch to let only when you actually need to reassign.
Uppercase constants
There’s a widespread practice of using constants as memorable aliases for hard-to-remember values that are known before the program runs. These get named in ALL_CAPS with underscores:
const SPEED_OF_LIGHT = 299792458; // metres per second
const EARTH_GRAVITY = 9.80665; // metres per second squared
const ABSOLUTE_ZERO = -273.15; // degrees Celsius
const AVOGADRO = 6.02214076e23; // particles per mole
// ...when we need one of them
let g = EARTH_GRAVITY;
alert(g); // 9.80665
Why bother:
EARTH_GRAVITYis far easier to remember than9.80665.9.80665is far easier to mistype thanEARTH_GRAVITY.- Reading the code,
EARTH_GRAVITYsays what it means;9.80665doesn’t.
So when should a constant be UPPERCASE, and when named normally? The deciding question is when the value becomes known.
A “constant” just means the value never changes after assignment. But some constants are known before execution (the speed of light), while others are computed at run time and simply never change afterwards:
const pageLoadTime = /* time taken by a webpage to load */;
pageLoadTime isn’t known until the page loads, so it gets an ordinary name — even though it’s still a constant. The UPPERCASE style is reserved for the first kind: aliases for hard-coded values baked in ahead of time.
Name things right
One more thing about variables — and it matters more than it looks.
A variable name should carry a clear, obvious meaning that describes the data inside it. Naming is genuinely one of the hardest skills in programming; you can often tell a beginner from a veteran at a glance, just from their variable names.
Here’s why it pays off. In a real project you spend most of your time modifying and extending existing code, not writing from a blank page. When you come back to code after a while, well-labelled data is the difference between “oh, obviously” and twenty minutes of re-reading. Good names are that labelling.
So spend a moment choosing the right name before you declare — it repays you many times over. Some rules that serve well:
- Use human-readable names like
userNameorshoppingCart. - Avoid cryptic abbreviations and single letters like
a,b,c— unless you truly know what you’re doing. - Be descriptive and concise.
dataandvalueare bad names: they say nothing. Only use them where context makes the meaning unmistakable. - Agree on vocabulary with your team and yourself. If a site visitor is a “user”, name related variables
currentUserornewUser— notcurrentVisitorornewManInTown.
Sounds simple? It is — and it isn’t. Doing it consistently in practice is the hard part. Go for it.
Summary
We store data in variables declared with let, const, or the older var:
let— the modern way to declare a variable you may reassign.const— likelet, but the value can never be reassigned. Prefer it by default; it guarantees and documents that the value is fixed.var— the old-school declaration. We generally avoid it, but its quirks are covered in The old “var” for when you meet it in legacy code.
And whatever the keyword: name your variables so anyone reading the code — including future you — instantly knows what’s inside the box.