Reading — step 1 of 7
Learn
A variable is a labeled box that holds a value. JavaScript has three keywords for declaring variables: var, let, and const. The decision tree for modern JavaScript is simple:
- Default to
const. Most variables don't need to change after their first assignment. - Use
letonly when you'll reassign. A loop counter, an accumulating value, a flag. - Avoid
var. Its scoping rules cause real bugs. We're not skippingvarbecause it's hard — we're skipping it because modern code doesn't use it.
Declaring with const and let
The = is assignment, not equality. Read it left-to-right: "the name on the left now refers to the value on the right."
const protects the BINDING, not the value
A common confusion: const doesn't make the value immutable, just the variable name. You still can't reassign the variable, but if it points at an object or array, you can mutate that object's contents:
The constant part is the reference, not the contents. To get true immutability, use Object.freeze() or libraries.
Block scope
Both const and let are block-scoped — they exist only within the { ... } block where they were declared:
This is what you'd expect from most languages. It prevents leaks and accidental clashes.
Why we avoid var
var is FUNCTION-scoped, not block-scoped. It also gets "hoisted" — accessible anywhere in the function before it's even declared:
That's a footgun. Modern code avoids it.
Naming rules
- Letters, digits,
_,$. Can't start with a digit. - Case-sensitive:
nameandNameare different. - Reserved words can't be names:
if,return,class, etc.
Convention: camelCase for variables and functions, PascalCase for classes, UPPER_SNAKE_CASE for true constants:
Common mistakes
- Using
==(loose equality) when checking values — use===. - Mistaking
constfor deep immutability. It only locks the binding. - Reaching for
letwhenconstwould do — if you don't reassign, preferconst. - Using
varbecause old tutorials still mention it.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…