JavaScript has three ways to declare a variable. Two of them you should use, one you should not.
const name = "Ada"; // use this by default
let score = 0; // use this when the value must change
var old = "avoid"; // legacy — do not use in new codeconst: cannot be reassigned#
const rate = 12;
rate = 15; // TypeError: Assignment to constant variable.Start with const. If you later find you genuinely need to reassign, change it to let. This habit makes code easier to follow, because every const is a promise that the name will keep meaning the same thing.
The important subtlety#
const stops you reassigning the name. It does not freeze the contents.
const scores = [10, 8];
scores.push(9); // fine — the array changed
console.log(scores); // [10, 8, 9]
scores = [1, 2]; // TypeError — the name cannot point somewhere newSame for objects: person.age = 37 is allowed on a const person.
let: reassignable#
let total = 0;
for (const price of [100, 250, 80]) {
total += price;
}
console.log(total); // 430Block scope#
let and const exist only inside the nearest pair of braces.
if (true) {
const secret = "hidden";
console.log(secret); // works
}
console.log(secret); // ReferenceError: secret is not definedThis is why var is avoided. var leaks out of blocks, which produces bugs that are painful to trace:
if (true) {
var leaked = "still here";
}
console.log(leaked); // "still here" — surprising and unhelpfulNaming#
- Start with a letter,
_or$; never a digit - No spaces or dashes
- Case sensitive:
userNameandusernamediffer - Convention is
camelCasefor variables and functions,PascalCasefor classes and React components,UPPER_SNAKEfor fixed configuration values
undefined versus null#
let a;
console.log(a); // undefined — declared but never given a value
const b = null;
console.log(b); // null — deliberately emptyRoughly: undefined means “nobody set this”, null means “someone set this to nothing on purpose”.
Two shortcuts worth knowing#
const name = user.name ?? "Guest"; // fallback only if null/undefined
const city = user?.address?.city; // no crash if address is missingThe second one prevents the very common “cannot read properties of undefined” error — see common JavaScript errors.
Questions people ask#
Should I ever use var?
Only when maintaining old code that already uses it. There is no reason to write new var declarations.
What if I forget the keyword entirely?
Writing score = 5 with no keyword creates a global variable, which is almost never what you want. Adding "use strict"; at the top of a file turns that into an error instead.
Is const faster?
No meaningful difference. Use it for clarity, not speed.