📘 JavaScript Data Types: Primitive vs Non-Primitive

🔰 Beginner Notes:

Primitive means simple data types that store a single value like a name or number. They are stored directly in memory.

Non-Primitive means complex data types like arrays, objects, and functions. They are stored by reference, which means they point to a memory address.

🧠 Analogy: Think of primitive as a piece of paper with a number, and non-primitive as a folder that holds many papers — you access it through a path (reference).

🟦 Primitive Data Types

Definition: These are basic, immutable values stored directly in memory.

🔍 Primitive Example Breakdown

let message = "Hello";
let score = 90;
let isValid = true;
let nothing = null;
let notAssigned;
let id = Symbol("userID");
let largeNumber = 123456789123456789123456789n; // BigInt

console.log(typeof message);      // string
console.log(typeof score);        // number
console.log(typeof isValid);      // boolean
console.log(typeof nothing);      // object (special case)
console.log(typeof notAssigned);  // undefined
console.log(typeof id);           // symbol
console.log(typeof largeNumber);  // bigint

🟩 Non-Primitive (Reference) Data Types

Definition: These hold references to objects and are mutable.

🔍 Non-Primitive Example Breakdown

let user = {
  name: "Ali",
  age: 25
};

let colors = ["red", "green", "blue"];

function greet() {
  console.log("Hello from function");
}

console.log(typeof user);    // object
console.log(typeof colors);  // object (array is type object)
console.log(typeof greet);   // function

📊 Comparison Table

Feature Primitive Non-Primitive
Stored by Value Reference
Mutable? ❌ No ✅ Yes
Compared by Value Reference
Example "Hi", 5, true [1,2,3], {name: "Ali"}

📌 Copying Behavior Example

// Primitive
let a = 10;
let b = a;
b = 20;
console.log(a); // 10 ✅ (copy)

// Non-Primitive
let obj1 = { name: "Ali" };
let obj2 = obj1;
obj2.name = "Sara";
console.log(obj1.name); // "Sara" ❗ (reference)

💡 Summary

Primitive types are simple and fast, stored directly in memory. Non-primitive types are flexible structures stored by reference, suitable for complex data.