JavaScript Internals (521 Qs)•Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)
What are the differences between primitives and non-primitives?
JavaScript language has both primitives and non-primitives but there are few differences between them as below,
| Primitives | Non-primitives |
|---|---|
| These types are predefined | Created by developer |
| These are immutable | Mutable |
| Compare by value | Compare by reference |
| Stored in Stack | Stored in heap |
| Contain certain value | Can contain NULL too |
Practical Code Example
javascript
// Primitives: Passed by VALUE, stored on stack, immutable:
let a = 10;
let b = a;
b = 20;
console.log(a); // 10 (unchanged)
// Non-Primitives (Objects): Passed by REFERENCE:
let obj1 = { name: 'John' };
let obj2 = obj1;
obj2.name = 'Bob';
console.log(obj1.name); // 'Bob' (mutated!)