After this lesson you will be able to create variables, give them sensible names, change them when needed, and know which of the three keywords, const, let and var, to use.
What a variable is
A variable is a name attached to a value, so that you can use the value again later. Without variables a program could only work with numbers and text typed out directly. With them it can remember things.
let score = 10;
score = score + 5;
console.log(score);This prints 15. The first line declares the variable score and gives it the value 10. The second line assigns a new value computed from the old one. The equals sign here does not mean "is equal to" as in maths. It means "store the value on the right in the name on the left".
const: the default choice
Use const for a value that you will not reassign.
const siteName = "Notes";
siteName = "Other"; // not allowedRunning that second line stops the program with TypeError: Assignment to constant variable. A const must also be given its value on the line where it is declared.
Using const by default makes your code easier to follow, because a reader knows the name always means the same thing. Switch to let only when you find you really need to change the value.
const does not freeze the contents
This surprises many beginners. const protects the name, not what the value contains.
const tags = ["html"];
tags.push("css");
console.log(tags); // [ 'html', 'css' ]That works, because the array itself is changed and tags still points at the same array. Only tags = somethingElse would be refused. Arrays and objects get their own lessons later.
let: for values that change
Use let for a value that has to be reassigned, such as a counter, a running total, or a flag that flips.
let attempts = 0;
attempts = attempts + 1;
attempts += 1; // a shorter way to say the same thing
console.log(attempts); // 2You can declare a let without a value. It then holds undefined, which means "nothing has been put here yet".
let nothing;
console.log(nothing); // undefinedTry the difference
This example shows let changing and const refusing to. The try and catch part catches the error so the page can report it. You will learn that properly in the errors lesson.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
let lines = [];
let score = 10;
score = score + 5;
lines.push("score is " + score);
const siteName = "Notes";
try {
siteName = "Other";
} catch (error) {
lines.push(error.name + ": " + error.message);
}
lines.push("siteName is still " + siteName);
out.textContent = lines.join("\n");
</script>Naming rules
A name can contain letters, digits, underscores and dollar signs, but:
- It cannot start with a digit:
2fastis invalid,fast2is fine. - It cannot contain spaces or hyphens:
my-nameis read as "my minus name". - It cannot be a reserved word such as
let,classorif. - It is case sensitive:
total,TotalandTOTALare three different variables.
Conventions matter just as much as rules:
- Use camelCase for ordinary variables:
userName,totalPrice. - Use names that say what the value means:
itemCountbeatsx, andisLoggedInbeatsflag. - Many programmers write true constants such as fixed limits in capitals:
MAX_ITEMS. This is a habit, not a rule of the language.
Block scope
A block is the code between a pair of curly braces. Variables made with let and const exist only inside the block where they are declared.
{
let inner = 1;
}
console.log(inner); // ReferenceError: inner is not definedThis is helpful: a variable cannot be touched from places that have no business with it. Scope gets a full lesson later in the course.
And var?
Before 2015, var was the only keyword. It still works and you will see it in older code and tutorials, but it behaves in surprising ways.
var v = 1;
var v = 2; // declaring it again is allowed, silently
console.log(v); // 2
function find() {
if (true) {
var leaked = "hi";
}
return leaked; // works: var ignores the braces of the if
}
console.log(find()); // hiA var is scoped to the whole function, not the block, and it can be redeclared without a warning. Both make mistakes harder to spot. For new code, use const and let and you will never need var.
Common mistakes
- Using
letfor everything. If a value never changes,constdocuments that and lets the language catch accidental changes. - Assuming
constmakes things unchangeable. It only blocks reassignment. An array or object stored in aconstcan still be edited. - Misspelling a name.
totlinstead oftotalgivesReferenceError: totl is not defined. Copy names rather than retyping when in doubt. - Declaring twice. Writing
let count = 1;and laterlet count = 2;in the same scope is a SyntaxError. Declare once, then assign withcount = 2;. - Using a variable before it is declared. Reading a
letorconstabove its declaration line throws an error. - Starting a name with a digit or adding a hyphen. Use
item2anditemCount.
Exercise
- Declare a
constcalledpricewith the value20and aletcalledquantitywith the value1. - Increase
quantityto3. - Print
price * quantitywithconsole.log. You should see60. - Try to reassign
priceand read the error message. - Rename each variable to something longer and clearer, and check it still works.
Next: Data types.
Key points
- A variable is a named place that holds a value, created with let or const.
- Use const by default, and let only when the value has to be reassigned.
- const stops reassignment, not change, so the contents of a const array or object can still be modified.
- let and const are block scoped, while var is function scoped and can leak out of blocks.
- Names are case sensitive, cannot start with a digit, and by convention use camelCase.