⬅ Previous Topic
Programming ParadigmsNext Topic ⮕
Primitive Data Types⬅ Previous Topic
Programming ParadigmsNext Topic ⮕
Primitive Data TypesA 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"
.
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.
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.
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.
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.
Why did changing arr2
affect arr1
?
Answer: Because they both reference the same object in memory, not independent copies.
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.
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.
⬅ Previous Topic
Programming ParadigmsNext Topic ⮕
Primitive Data TypesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.