Declaring Variables with var
You'll learn how to create variables using JavaScript's original var keyword and understand why it's mostly avoided in modern code.
What is var?
Before 2015, var was the only way to declare variables in JavaScript. It tells the engine "I want to store a value and give it a name." You can think of it like putting a label on a box where you'll keep something — the label is your variable name, and the contents can change.
var age = 25;
var name = "Alice";
var isStudent = true;
Why var Behaves Differently
Unlike modern alternatives you'll learn later, var has quirky behavior that often surprises beginners:
Function scope (not block scope): Variables declared with var are visible throughout the entire function they're declared in, ignoring curly braces from things like if statements. This is like having a label that's readable anywhere in a room, even if you put it in a corner.
Hoisting: JavaScript "lifts" var declarations to the top of their scope before running your code, which can lead to confusing situations where you reference a variable before you've written its declaration.
Re-declaration allowed: You can accidentally declare the same variable twice with var, and JavaScript won't complain — it just overwrites silently.
Why It Matters
You'll encounter var in older code and tutorials, so recognizing it is important. However, most developers now use newer alternatives that fix these problems.
Key Takeaway: var is JavaScript's original variable keyword, but its function-scoped and hoisting behavior makes it unpredictable compared to modern alternatives — recognize it when you see it, but prepare to learn better options.