Non-Primitive Data Types in JavaScript (Objects)
Non-Primitive (Reference) Data Types → Store collections or complex data and are mutable.
Non-primitive types are also known as reference types because they are stored and accessed by reference, not by value.
- Stored by reference, not by value.
- Mutable — can be changed after creation.
- Declared using object literals, constructors, or classes.
- All non-primitive types are derived from the Object base type.
Types of Non-Primitive (Reference) Data Types
Object
Objects are the foundation of all non-primitive types in JavaScript.
They store data in key–value pairs.
Example:
let person = {
name: "Alice",
age: 25,
city: "Delhi"
};
console.log(person.name); // Output: Alice
Array
An array is a special kind of object used to store ordered collections of values.
Each value has an index (starting from 0).
Example:
let colors = ["red", "green", "blue"];
console.log(colors[1]); // Output: green
colors.push("yellow"); // Adding new element
console.log(colors); // ["red", "green", "blue", "yellow"]
Function
Functions are callable objects used to perform actions or calculations.
In JavaScript, even functions are treated as objects.
Example:
function greet(name) {
return "Hello " + name + "!";
}
console.log(greet("John")); // Output: Hello John!
Extended (Built-in) Object Types
JavaScript provides several built-in object types that are also non-primitive:
Date
A built-in object to handle dates and times.
Example:
let today = new Date();
console.log(today);
RegExp (Regular Expression)
Used for pattern matching and string searching.
Example:
let pattern = /hello/i;
console.log(pattern.test("Hello world")); // Output: true
Map
Stores key–value pairs where keys can be any data type (not just strings).
Maintains insertion order.
Example:
let map = new Map();
map.set("name", "John");
map.set("age", 30);
console.log(map.get("name")); // Output: John
Set
Stores unique values (no duplicates).
Example:
let numbers = new Set([1, 2, 3, 3]);
console.log(numbers); // Output: Set(3) {1, 2, 3}
WeakMap and WeakSet
Similar to Map
and Set
, but they only store weakly held references to objects.
Useful for memory management (garbage collection).
Example:
let weakMap = new WeakMap();
let obj = {};
weakMap.set(obj, "some value");
Primitive vs Non-Primitive
Feature | Primitive | Non-Primitive |
---|---|---|
Storage | Stored by value | Stored by reference |
Mutability | Immutable | Mutable |
Memory | Stored in stack | Stored in heap |
Comparison | Compared by value | Compared by reference |
Examples | string , number , boolean | object , array , function |