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
letandconst. - 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
camelCasefor variables and functions;PascalCasefor 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
varleads to function-scoped variables and hoisting surprises. - Reassigning
constbindings throws; for objects, the binding is constant but contents can mutate.
Checks for Understanding
- When should you choose
const? - Is
letblock-scoped or function-scoped?
Show answers
- Default to
constfor bindings that won’t be reassigned. letis block-scoped.
Exercises
- Refactor a snippet using
varto uselet/constappropriately; explain your choices. - Create a constant object and mutate one of its properties; explain why this is allowed.