A variable is a named container for a value. Instead of writing the number 25 everywhere in your code, you can store it once in a variable and refer to it by name — which makes code easier to read and easier to change.
In JavaScript, you declare a variable with let and give it a value with =:
let score = 0;
let playerName = "Alex";
console.log(score); // 0
console.log(playerName); // AlexThe whole point of a variable is that its value can change while the program runs — that's where the name comes from.
let score = 0;
score = 10;
score = score + 5;
console.log(score); // 15A variable name must start with a letter, _, or $ — not a digit — and can't contain spaces. Good names describe what the value is for.
| Good | Works, but unclear |
|---|---|
| userAge | x |
| totalPrice | tp |
| isLoggedIn | flag1 |
JavaScript variable names are case-sensitive: score and Score are two different variables.