JavaScript Coding Day 8 | Primitive Data Types & Non-Primitive Data Types
Primitive Data Types & Non-Primitive Data Types
Watch the lesson tutorial 🔻
1. Primitive Data Types
Primitive data types are the simplest forms of data. In JavaScript, they are immutable (cannot be changed) and strictly stored by value. When you assign a primitive value to a new variable, JavaScript creates a completely separate copy of that value.
Common Primitive Types: Number, String, Boolean, Undefined, Null.
Practical Example (Pass by Value)
In this example, b becomes a copy of a. Because they are primitive, they are independent of each other.
let a = 50;
let b = a; // JavaScript creates a copy of the value 50 for 'b'
b = 60; // Changing 'b' does not affect 'a'
console.log(a);
// Output: 50
// Reason: Primitive data types are passed by "Value".
// When we said 'let b = a', 'b' got its own copy of the number 50.
// Modifying 'b' essentially changes the copy, leaving the original 'a' untouched.
2. Non-Primitive Data Types
Non-primitive data types (often called Reference Types) are more complex. They include Objects, Arrays, and Functions.
Instead of storing the actual data directly in the variable, JavaScript stores a reference (a memory address) that points to where the data is stored in memory (the Heap). When you copy a non-primitive, you are only copying the address, not the actual object.
Practical Example (Pass by Reference)
In this example, both o and p point to the exact same object in memory.
const o = { name: "Chiru" };
const p = o; // 'p' receives the REFERENCE (address) to the same object as 'o'
p.name = "ChiruCodes"; // We change the data inside that shared memory location
console.log(o);
// Output: { name: "ChiruCodes" }
// Reason: Non-primitive data types are passed by "Reference".
// 'o' and 'p' are like two different keys opening the exact same door.
// If you use key 'p' to open the room and rearrange the furniture (change the name),
// the room looks different when you look through key 'o'.
Difference: Primitive vs. Non-Primitive
Here is a comparison table to summarize the differences for your readers.
| Feature | Primitive Data | Non-Primitive Data |
| Examples | Number, String, Boolean, Null | Object, Array, Function |
| Storage | Stores the actual value. | Stores a reference (address) to the value. |
| Mutability | Immutable (cannot be changed). | Mutable (can be modified). |
| Comparison | Compared by value (5 === 5 is true). | Compared by reference ([] === [] is false). |
| Memory | Stored in the Stack. | Stored in the Heap. |
- by Chirana Nimnaka

Comments
Post a Comment