Lesson 29 of 296
Variables: let and const
What you will learn
- What a variable is
- How to create a variable with
letandconst - The difference between creating and changing a variable
- Naming rules and naming style
- Why you should use
constby default
On this page
- What is a variable?
- let: a value that can change
- const: a value that cannot be replaced
- Create once, change many times
- The right side is worked out first
- Variables do not update themselves
- Which one to use?
- A note about const with objects and arrays
- var: the old way
- Naming rules (must follow)
- Naming style (should follow)
- Common mistakes
- How to say it in an interview
- Key words
What is a variable?
A value is a piece of data, such as 30 or "Sam". A variable is a named box that holds a value, so you can use the value later by its name.
let age = 30;| Part | Meaning |
|---|---|
let | "Create a new variable" |
age | The name of the variable |
= | "Put this value in the box" (called assignment) |
30 | The value |
Now you can use the name:
console.log(age); shows: 30
console.log(age + 1); shows: 31When JavaScript sees a variable name without quotes, it replaces the name with the value inside.
console.log(age); shows: 30 (the value)
console.log("age"); shows: age (just text)let: a value that can change
let score = 10;
score = 15;
console.log(score); shows: 15The first line creates the variable. The second line changes its value. Notice: no let when changing.
const: a value that cannot be replaced
const birthYear = 1996;
birthYear = 2000; Error: Assignment to constant variable.A const variable must get its value when it is created, and you cannot put a new value in it later.
Create once, change many times
You can only create a variable with the same name once in the same block of code.
let count = 1;
let count = 2; Error: Identifier 'count' has already been declaredTo change it, leave out let:
let count = 1;
count = 2; fineThe right side is worked out first
let score = 10;
score = score + 5;Read the second line from the right: take the current value of score (10), add 5, then put the result (15) back into score.
Variables do not update themselves
let price = 3;
let quantity = 4;
let total = price * quantity; total is 12
quantity = 5;
console.log(total); still 12total was calculated once, when that line ran. Changing quantity later does not change total. You must calculate it again:
total = price * quantity; now 15Which one to use?
Use const by default. Use let only when the value really needs to change later, such as a counter in a loop or a running total.
Why? When you read const, you know straight away the value will never be replaced. That makes code easier to understand and stops accidental changes.
A note about const with objects and arrays
const stops you replacing the value. It does not stop you changing what is inside an array or object:
const list = [1, 2];
list.push(3); fine: list is now [1, 2, 3]
list = [9]; Error: you cannot replace itYou will learn arrays and objects in Lessons 40 and 41, and the full reason in Part 5.
var: the old way
Before 2015, the only way to create a variable was var. You will still see it in old code. It has confusing rules (Part 5 explains them). Do not use var in new code.
Naming rules (must follow)
- Can contain letters, numbers,
_and$. - Cannot start with a number.
2namesis not allowed. - No spaces or hyphens.
first nameandfirst-nameare not allowed. - Cannot be a reserved word that JavaScript uses itself, such as
let,const,if,return,class. - Case-sensitive:
totalandTotalare two different variables.
Naming style (should follow)
- Use camelCase: the first word in small letters, each next word starts with a capital:
firstName,totalPrice,isLoggedIn. - Use clear, full names:
coffeePrice, notcporx. - Start true/false variables with
is,hasorcan:isAdmin,hasPaid,canEdit. - Fixed settings that never change are sometimes written in capitals:
MAX_UPLOAD_SIZE.
Interviewers notice variable names. Good names are a sign of a good developer.
Common mistakes
- Using
letagain when changing a variable. - Expecting a calculated variable to update by itself.
- Spelling the name differently later (
totalvstotl): JavaScript says "not defined". - Capital letters:
Const,Letare errors. - One-letter names in real code.
How to say it in an interview
"A variable is a named reference to a value. let allows reassignment, const does not. I use const by default and let only when a value must change, like a counter. const prevents reassignment but does not make objects or arrays unchangeable. I avoid var because of its function scope and hoisting behaviour."
Key words
| Word | Meaning |
|---|---|
| Value | A piece of data |
| Variable | A named box that holds a value |
| Declare | Create a variable |
| Assign | Put a value into a variable, using = |
| Reassign | Put a new value into an existing variable |
| camelCase | Naming style: firstName, totalPrice |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.