The Basic Idea
Think of a variable like a name tag stuck on a value.
- Simple values (numbers, strings, true/false) — each variable gets its own separate value.
- Objects and arrays — variables can share the same value.
That's really the whole concept. Everything else is just examples of this playing out.
1. Simple Values Are Independent
Numbers, strings, and booleans are "simple" (also called primitive) values. When you copy them into a new variable, you get a totally separate copy.
let age1 = 5;
let age2 = age1; // age2 gets its own copy of the number 5
age2 = 10; // change age2 only
console.log(age1); // 5 <- did not change
console.log(age2); // 10
Changing age2 never touches age1. They're two separate values now, even though they started out equal.
2. Objects and Arrays Can Be Shared
Objects and arrays work differently. When you copy them into a new variable, you're not making a new object — you're just giving the same object a second name tag.
let cart1 = { items: 5 };
let cart2 = cart1; // cart2 is just another name for the SAME object
cart2.items = 10; // change it using cart2
console.log(cart1.items); // 10 <- cart1 changed too!
cart1 and cart2 are pointing at the exact same object. Change it through one name, and it shows up through the other name too.
Simple rule: primitives copy the value. Objects copy the pointer to the value.
3. What This Means Inside Functions
If you reassign a parameter inside a function, it never affects the original variable — this is true for everything, even objects:
function setToHundred(number) {
number = 100; // this only changes the LOCAL copy inside the function
}
let myNumber = 5;
setToHundred(myNumber);
console.log(myNumber); // still 5
But if you mutate (edit) an object's property inside a function, the original object changes too — because it's the same object:
function setToHundred(person) {
person.age = 100; // this edits the SHARED object, not a copy
}
let myPerson = { age: 5 };
setToHundred(myPerson);
console.log(myPerson.age); // 100 <- it changed!
So remember:
- Reassigning
=a whole variable → stays local, doesn't leak out. - Editing a property on an object → changes the real object everywhere.
4. Comparing Objects
=== checks whether two things are the exact same object in memory — not whether they look the same.
console.log({} === {}); // false <- two different empty objects
console.log([] === []); // false <- same reason, two different arrays
let box1 = { size: 1 };
let box2 = box1; // same box, two names
console.log(box1 === box2); // true <- same object
Top comments (0)