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.

JavaScript
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.

JavaScript
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.

FeaturePrimitive DataNon-Primitive Data
ExamplesNumber, String, Boolean, NullObject, Array, Function
StorageStores the actual value.Stores a reference (address) to the value.
MutabilityImmutable (cannot be changed).Mutable (can be modified).
ComparisonCompared by value (5 === 5 is true).Compared by reference ([] === [] is false).
MemoryStored in the Stack.Stored in the Heap.

- by Chirana Nimnaka

Comments

Popular posts from this blog

Python Coding Day 1 | The print() Function and Comments

What is Python?

Set Up an Environment to Code in Python