Variables
Your program needs memory: a place to remember the user's name, a product's price, or whether someone is logged in. That's what variables are for.
A variable is, at heart, a name that points to a value stored in memory. It lets you reuse data and give it a meaningful name, instead of repeating the same value all over the place.
let and const
let age = 25; // can change later
const name = "Ana"; // constant: cannot be reassigned
- Use
constby default: it makes clear the value won't change. - Use
letwhen you need to reassign the variable. - Avoid
var(the old way): it has confusing scope rules.
Reassigning
let points = 0;
points = points + 10; // now it's 10
If you try to reassign a const, JavaScript throws an error.
⚠️ Classic trap:
constdoesn't mean "immutable value", it means you can't reassign the name. If you store an object or an array in aconst, its contents can still change. What stays fixed is what the variable points to, not what's inside.
Variable names
- They can contain letters, numbers,
_and$, but can't start with a number. - By convention camelCase is used:
myAge,fullName. - Choose descriptive names:
totalPriceis better thanx.
Examples
Declaring and using variables
const name = "Ana";
let age = 25;
age = 26; // birthday 🎂
console.log(name, "is", age, "years old");