Loading lessons...
JavaScript Variables
JavaScript Variables
A variable is a named container for storing data values.
Declaring variables
In modern JavaScript, you declare variables with let or const:
let name = "Ada";
let age = 36;
const pi = 3.14;
The three ways
| Keyword | Can change later | Modern choice |
|---|---|---|
let | yes | preferred for changing values |
const | no | preferred when the value never changes |
var | yes | old way, avoid in new code |
Assigning values
Use the assignment operator = to put a value into a variable:
let price = 10;
price = 15; // change the value
Using variables
Once declared, use the variable name wherever you need the value:
let firstName = "Ada";
let lastName = "Lovelace";
let fullName = firstName + " " + lastName;
Undeclared variables
Using a variable before declaring it causes an error. Always declare variables before you use them.
TL;DR
- A variable stores a value under a name.
- Use
letfor values that change andconstfor fixed values. varis the old way; avoid it.=assigns a value to a variable.