Chapter II · Variables & Values
Variables
A variable is a named container in memory used to store, retrieve, and update data throughout your program.
01 What is a Variable?
Programs need a way to hold onto data while they run — user names, calculated scores, settings states. A variable is a named identifier that points to a specific value stored in memory.
Instead of remembering raw memory addresses, your code uses the variable name to fetch or modify the stored value whenever needed.
02 Simple Example
Declaring a variable and storing a value inside it.
let score = 42;
console.log(score); // 42
score = 50;
console.log(score); // 50
The variable score points initially to 42 and is later updated to point to 50.
03 How It Works
When you declare a variable, the JavaScript engine allocates space in memory and creates a binding between the identifier name and that memory reference.
Variables act as labeled boxes or references pointing to values stored in engine memory.
04 Step-by-Step
The engine parses the variable declaration statement.
An identifier binding is created in the current lexical environment.
The assigned expression is evaluated to a value.
The identifier is bound to reference that value in memory.
05 Mental Model
"A variable is a labeled storage box on a shelf."
You can look inside the box, replace its contents with something new, or use its label to reference it anywhere in your scope.
06 Common Mistakes
Thinking a variable "is" its value. It's more accurate to say a variable holds a reference to a value. This distinction barely matters for primitives like numbers and strings, but it becomes critical with objects and arrays — see "Object References" and "Reference vs. Value" later in this book.
Best practice: name variables for what they represent, not their type (userAge, not numVar). Types can change during refactors; meaning shouldn't.
07 Interview Questions
Q: What's the difference between declaring and initializing a variable?
Declaring creates the binding (let x;); initializing assigns it a first value (x = 5). They can happen together or separately.
Q: What happens if you use a variable before declaring it?
Depends on the keyword — var gives you undefined (hoisted), while let/const throw a ReferenceError due to the temporal dead zone.
Key Takeaway
Variables are named identifiers bound to memory locations, allowing programs to store and manipulate dynamic values.