đź§  JavaScript: Primitive vs Reference Types

When you’re assigning a variable in JavaScript, do you ever pause to wonder whether you’re copying the value—or a reference to something deeper? This question matters more than you think.

Let’s break down the difference between primitive types and reference types, using simple examples and visuals.

🔸 Primitive Types

Primitive types include string, number, boolean, undefined, null, bigint, and symbol.

They’re stored directly in memory and passed by value.

Here, changing b does not affect a. They’re separate values in memory.

🔹 Reference Types

Objects, arrays, and functions fall under reference types. These are stored in the heap, and variables just hold a reference to their memory address.

🖼️ Code Output Example:

Both person1 and person2 point to the same object, so changing one affects the other.

✍️ Final Thoughts

This is one of those JavaScript quirks that leads to unexpected bugs if you’re unaware of what’s happening under the hood. Just remember:

  • Primitives are copied by value.

  • References are… well, shared.

Understanding this will level up your debugging skills and help you write safer, more predictable code.

Leave a Reply

Your email address will not be published. Required fields are marked *