JavaScript Variables
A variable is a named store for a value. A program reads and changes the value through the name.
Declare and log
let declares the variable city. The = sign stores the text Oslo in it.
let city = "Oslo";
console.log(city);Change the value
A variable can hold a new value. The second assignment replaces the first value.
let city = "Oslo";
city = "Bergen";
console.log(city);Two variables
One program can hold many variables. Each name holds its own value.
let city = "Oslo";
let country = "Norway";
console.log(city);
console.log(country);Example
let player = "Ana";
let score = 10;
console.log(player);
console.log(score);
score = 20;
console.log(score);Key points
- A variable stores a value for later use.
- let: the keyword that declares a variable
- The = sign assigns a value to a variable.
- A variable name can hold letters, digits, _ and $.
- A variable name cannot start with a digit.
- Variable names are case-sensitive, so age and Age differ.
In this example, the first statement declares player with the value Ana. The second statement declares score with the value 10. The next two statements print both values. The fifth statement changes score to 20, and the last statement prints the new value.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which line declares a variable named age with the value 9?