Getting started · Lesson 2 of 45
Variables: let, const and var
How to store a value for later, and pick the right keyword.
A variable is a named box where you keep a value for later. There are 3 ways to declare one:
const: the value won't change. Use it by default.let: the value will change (a counter, a total, a state).var: the old way. You'll see it in old code, but don't use it.
Each variable is a name pointing at a value.
- ▶const name = "Omar"
- 2let score = 10
- 3score = score + 5
- 4console.log(name, score)
Variables
| name | "Omar" |
Output
name is created with "Omar" and will never change.
Why not var?
| const | let | var | |
|---|---|---|---|
Can change? | No | Yes | Yes |
Scope | block | block | function |
Use before declaring? | error | error | gives |
Declare twice? | error | error | allowed (risky) |
Naming rules
A name starts with a letter, _ or $, has no spaces, and isn't a reserved word like let or if. The convention is camelCase: userName, totalPrice. JavaScript is case-sensitive: age and Age differ.
Quick question
A product's price changes in a sale. How do you declare it?
Spot the bug
One line will throw an error. Click it.
Complete the code
Complete it: the student count grows, the course name is fixed.
course = "JavaScript" students = 20 students = students + 1
Exercise
Create balance with 100, add 50, and print it.
Expected output: 150
// balance
Learn more from
Played 0 of 4 games
Sign in to save your progress and earn XP.