Skip to the content

Lesson 29 of 296

Variables: let and const

What you will learn

  • What a variable is
  • How to create a variable with let and const
  • The difference between creating and changing a variable
  • Naming rules and naming style
  • Why you should use const by default
On this page

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;
PartMeaning
let"Create a new variable"
ageThe name of the variable
="Put this value in the box" (called assignment)
30The value

Now you can use the name:

console.log(age);        shows: 30
console.log(age + 1);    shows: 31

When 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: 15

The 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 declared

To change it, leave out let:

let count = 1;
count = 2;               fine

The 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 12

total was calculated once, when that line ran. Changing quantity later does not change total. You must calculate it again:

total = price * quantity;        now 15

Which 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 it

You 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. 2names is not allowed.
  • No spaces or hyphens. first name and first-name are not allowed.
  • Cannot be a reserved word that JavaScript uses itself, such as let, const, if, return, class.
  • Case-sensitive: total and Total are 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, not cp or x.
  • Start true/false variables with is, has or can: 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 let again when changing a variable.
  • Expecting a calculated variable to update by itself.
  • Spelling the name differently later (total vs totl): JavaScript says "not defined".
  • Capital letters: Const, Let are 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

WordMeaning
ValueA piece of data
VariableA named box that holds a value
DeclareCreate a variable
AssignPut a value into a variable, using =
ReassignPut a new value into an existing variable
camelCaseNaming style: firstName, totalPrice

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.