A variable is a labelled box that holds a value, and JavaScript gives you three keywords for making one.
Complete lesson & earn 250 PX
EXERCISE
1A variable gives a name to a value so that you can store it once and then use it as many times as you like.
EXERCISE
2Three keywords create variables, and choosing between them is one of the first habits that separates careful code from careless code.
EXERCISE
3The rules for what a name is allowed to be are short, but the habits for what a name should be are what make code readable.
A variable is a name you attach to a value so you can use that value again without writing it out each time. You choose the name and JavaScript remembers what it points at. That is the whole idea, and almost every line you write from here on will use one.
Creating one takes three parts:
let score = 0;
let is the keyword that creates the variable. score is the name, which you choose. 0 is the value being stored. The order never changes.
Once it exists, the name stands in for the value everywhere:
let name = "Bob";
console.log(name); // Bob
console.log(name.length); // 3
console.log("Hi, " + name); // Hi, Bob
Nothing copies the text three times. Each line asks for whatever name currently holds, and uses that.
Which means changing it once changes it everywhere it is used afterwards:
let name = "Bob";
console.log("Hi, " + name); // Hi, Bob
name = "Alice";
console.log("Hi, " + name); // Hi, Alice
This is the actual point of variables, and it is easy to miss when the examples are short. A price that appears in nine places in a real program is stored once and read nine times. Change the one place it is stored and all nine are correct. Write the number out nine times and you have nine places to get wrong.
Declaring without a value is allowed:
let winner;
console.log(winner); // undefined
winner = "Bob";
console.log(winner); // Bob
undefined is not an error, and it is not zero or empty text. It is reporting that the name exists and nothing has been put in it yet. You will see it often, and reading it as declared but not set rather than as a failure will save you confusion later.
Pro Tip: Assignment runs right to left.
let score = 0does not mean "score equals zero" the way it would in mathematics; it means "work out the value on the right, then store it in the name on the left". That reading makescount = count + 1sensible instead of impossible: work outcount + 1first, then put the answer back intocount.
Three keywords create variables. const is for a value you will not reassign, let is for one you will, and var is the original keyword from 1995 which still works but behaves in a way that catches people out.
const refuses to be pointed at something else:
const siteName = "DevLoom";
siteName = "Something else";
// TypeError: Assignment to constant variable.
That error is the feature. Most values in real code are set once and read many times, and const turns an accidental reassignment into an immediate, obvious failure rather than a value that quietly became something you did not expect.
const pi = 3.14159; // never changes: const is correct
let visitors = 0; // changes constantly: let is correct
visitors = visitors + 1;
console.log(visitors); // 1
There is one thing about const that nearly everyone gets wrong at first. It protects the name, not the contents:
const user = { name: "Ada" };
user.name = "Grace";
console.log(user.name); // Grace
That is allowed, and it is not a loophole. const promises that user will always point at this same object. It says nothing about what is inside the object. Changing a property does not move the name.
user = { name: "Alan" };
// TypeError: Assignment to constant variable.
That is not allowed, because it does move the name, to a different object entirely. The same distinction applies to arrays: scores.push(3) is fine on a const, and scores = [1, 2, 3] is not.
var is the one to avoid, and this is why:
if (true) {
var a = "I leak out";
let b = "I stay in";
}
console.log(a); // I leak out
console.log(b); // ReferenceError: b is not defined
var does not recognise the curly braces at all. a was declared inside the if and is still readable outside it. let and const behave the way the braces suggest. In a short example that is a curiosity; in a two-hundred-line function it is a variable you thought was temporary still holding a value three screens later.
Pro Tip: Reach for
constfirst, every time, and switch toletonly at the moment you find you need to reassign. You will writeconstfar more often thanlet, and each accidental reassignment the language catches is a real bug found for free. Treatvaras something you read in older code rather than something you write.
JavaScript will accept almost any name you give a variable. Your future self reading the code will not be so accommodating. There are rules the language enforces, and separately there are habits that decide whether the code can be understood six months later.
The rules are short:
let firstName = "ok"; // letters, and the normal style
let user_name = "ok"; // underscores are legal
let $price = "ok"; // $ is legal
let item2 = "ok"; // digits are legal, but not first
And what is rejected:
let 2fast = "no"; // SyntaxError: cannot start with a digit
let my-name = "no"; // SyntaxError: a hyphen means subtraction
let class = "no"; // SyntaxError: reserved word
Capitalisation counts, and this catches everybody exactly once:
let userName = "Ada";
console.log(username);
// ReferenceError: username is not defined
userName and username are two unrelated names as far as the language is concerned. The error is helpful here, because the name genuinely does not exist. The version of this that costs real time is when both spellings exist and you update the wrong one.
Now the habits, which matter more than the rules. A name should say what the value means:
let d = 86400;
let p = 19.99;
let t = p * 1.2;
Every one of those is legal and every one is useless. d could be days, distance, discount or date. Reading the next hundred lines is the only way to find out, and you will have to do it again next month.
const secondsPerDay = 86400;
const basePrice = 19.99;
const priceWithTax = basePrice * 1.2;
Identical behaviour, and now the third line explains itself. The convention JavaScript uses is camelCase: the first word lowercase, each following word capitalised. Booleans read well when they start with is, has or can, because the name then answers a yes-or-no question:
const unreadMessageCount = 12;
const hasAcceptedTerms = true;
const isLoggedIn = false;
Name a value for what it means, not for its type or where it came from. data, temp, result and info are the four most common poor names in the language, because each of them is true of almost any value and therefore tells the reader nothing. If you cannot think of a meaningful name, that is often a signal that you have not yet worked out what the code is really doing.
const for a value that will not be reassigned, let for one that will, var only when reading older code. Reach for const first and switch to let when you actually need to reassign.