Understanding Variables
and Memory



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

Key Questions to Ask Yourself

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.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M