What is a Variable?
A variable is like a labeled storage box in memory that holds a value. It lets you store data (like numbers or text), give that data a name, and access or change it later in your program.
You can think of it as:
let x = 10
let name = "Alice"
Here, x
stores the number 10
, and name
stores the text "Alice"
.
How Memory Works with Variables
When a variable is created, a space in memory is reserved for it. The value is stored in that space, and the variable name acts as a label pointing to it.
Example: Simple Memory Model
let a = 5
let b = a
b = 10
Output:
a = 5 b = 10
Explanation: When b = a
, it copies the value of a
into b
. Changing b
later does not affect a
because they occupy different memory locations.
Question:
Is the value copied or referenced when you assign one variable to another?
Answer: For primitive data types like numbers and booleans, the value is copied. Each variable then lives in a separate memory location.
Variables with Reference Types
For collections like arrays or objects, variables store a reference (a pointer) to the memory location, not the actual value.
let arr1 = [1, 2, 3]
let arr2 = arr1
arr2[0] = 99
Output:
arr1 = [99, 2, 3] arr2 = [99, 2, 3]
Here, both arr1
and arr2
point to the same memory location, so changes via one variable affect the other.
Question:
Why did changing arr2
affect arr1
?
Answer: Because they both reference the same object in memory, not independent copies.
Understanding Assignment vs Mutation
Assignment changes where the variable points. Mutation changes the content at the memory location.
let list = [1, 2]
let backup = list
list = [3, 4] // reassignment
Output:
backup = [1, 2] list = [3, 4]
Reassignment makes list
point to a new array. backup
still points to the old array.
Tips for Beginners
- Variables are just names pointing to values in memory.
- Primitive values (like numbers, strings) are copied when assigned.
- Reference types (like lists, dictionaries) share the same memory location unless explicitly copied.
- Changing a reference variable can affect all variables pointing to the same reference.
Key Questions to Ask Yourself
- Is this variable holding a value or pointing to something?
- Am I creating a copy or just another reference?
- Will changing this variable affect another one?
Conclusion
Understanding how variables work is foundational to programming. It helps prevent bugs and lets you write more efficient and predictable code. Always remember: names point to memory, and what’s in that memory depends on the type of data you’re working with.