Variable Initialization
What you'll learn: You'll understand when variables receive their initial values and what happens if you don't provide one.
What Is Variable Initialization?
Initialization is the moment you give a variable its first value. This can happen at the same time you declare the variable, or later in your code.
Think of it like labeling a box (declaration) versus actually putting something inside it (initialization). You can do both at once, or label the box first and fill it later.
Initializing at Declaration
You can assign a value right when you declare a variable:
let age = 25;
const name = "Alex";
var isStudent = true;
Here, age, name, and isStudent are declared and initialized in one step.
Declaring Without Initializing
With let and var, you can declare a variable without giving it a value immediately:
let score;
var temperature;
What's inside these variables? They automatically contain undefined — the special primitive value that means "no value yet." JavaScript gives you undefined as a placeholder.
const Requires Initialization
You must initialize a const when you declare it. This won't work:
const country; // Error!
Why? Because const prevents reassignment. If you couldn't set it at declaration, you'd never be able to set it at all.
Why This Matters
Understanding initialization helps you avoid bugs. If you try to use an uninitialized variable, you'll get undefined, which might cause unexpected behavior. Always be intentional about when and how you give variables their first values.
Key Takeaway: Variables can be initialized at declaration or later (except const, which must be initialized immediately); uninitialized let and var variables automatically hold undefined.