Primitive vs Non-Primitive - Javascript: concise format


1️⃣ Primitives:

Primitives(number, string, boolean, null, undefined, symbol, and bigInt) are the chill dudes of JavaScript.

They’re passed by value, meaning when you assign one to a variable, you get a fresh copy in memory. Change the copy? The original doesn’t care. It’s like lending your friend a photocopy of your notes, they can scribble all over it, and your original still stays untouched!


Check This Code:

let cash = 100;
let wallet = cash;
wallet = 500;
console.log(cash); // 100 (Original is untouched, baby!)        

Why It Works: Primitives live in the stack memory, where each variable gets its own slot. No shared drama, no side effects. Perfect for when you want variables to mind their own business! 😎


2️⃣ Objects & Arrays: The Tricky Reference Trap :

Objects, arrays, and functions are different beasts. These are non-primitives and are passed by reference. When you assign an object to a new variable, you’re not copying it; you’re just pointing to the same memory address in the heap. Change one reference, and boom every variable pointing to that object changes its value . In JS, Object and Arrays are the same things at their core, they have only syntax differences.

Code That Proves It:

let profile = { name: "Alex" };
let clone = profile;
clone.name = "Max";
console.log(profile); // { name: "Max" } (Wait, what?! Original changed too!)        

The Catch: Both profile and clone are just pointers to the same object in memory. Mutate one, and they all reflect it. This is why objects and arrays can trip you up if you’re not careful! 😵


3️⃣ Real-World Scenarios to Nail It

Let’s get practical with some scenarios that’ll make this crystal clear:

Scenario 1: Function Arguments

Primitives in Functions: Pass a number to a function, and the original stays safe.

let score = 100;
function updateScore(val) { val = 200; }
updateScore(score);

console.log(score); // 100 (No change, bro!)        

Objects in Functions: Pass an object, and it’s mutation city!

let user = { id: 1, name: "Sam" };

function updateUser(obj) { obj.name = "Tom"; }

updateUser(user);

console.log(user); // { id: 1, name: "Tom" } (Original got hit!)        

Fix: Clone the object first with { ...user } or structuredClone(user) to keep the original safe.

Scenario 2: Reassignment vs. Mutation

- Reassignment: Breaks the reference.

let arr1 = [1, 2, 3];

let arr2 = arr1;

arr2 = [4, 5, 6]; // New array, new reference

console.log(arr1); // [1, 2, 3] (Original stays put)        

- Mutation: Affects all references.

let data = { role: "Dev" };

let copy = data;

copy.role = "Lead";

console.log(data); // { role: "Lead" } (Both changed!)        

4️⃣ Upcoming Topics For Deep Understanding -

  1. Shallow vs. Deep Copy.
  2. Object.freeze()? And did we need full object.freeze

#JavaScript #WebDevelopment #CodingTips #TechLife

To view or add a comment, sign in

Others also viewed

Explore topics