JavaScript - Variables
Overview
Estimated time: 15–25 minutes
Variables store values for later use. In modern JavaScript, prefer let
and const
over var
.
Learning Objectives
- Declare variables and initialize values.
- Choose between
let
andconst
. - Follow clear naming and scoping conventions.
Prerequisites
Declaring variables
let count = 0; // changeable
const pi = 3.14159; // constant binding
// Avoid var in modern code (function-scoped, hoisted)
Naming
- Use letters, digits,
_
,$
; cannot start with a digit. - Use
camelCase
for variables and functions;PascalCase
for classes. - Be descriptive:
userCount
,totalPrice
.
Initialization and reassignment
let total = 10;
total = total + 5; // ok
const max = 100;
// max = 200; // TypeError: Assignment to constant variable.
Common Pitfalls
- Using
var
leads to function-scoped variables and hoisting surprises. - Reassigning
const
bindings throws; for objects, the binding is constant but contents can mutate.
Checks for Understanding
- When should you choose
const
? - Is
let
block-scoped or function-scoped?
Show answers
- Default to
const
for bindings that won’t be reassigned. let
is block-scoped.
Exercises
- Refactor a snippet using
var
to uselet
/const
appropriately; explain your choices. - Create a constant object and mutate one of its properties; explain why this is allowed.