J

JavaScript Handbook

Clean • Professional

Non-Primitive Data Types

2 minute

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

learn code with durgesh images

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:

learn code with durgesh images

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

FeaturePrimitiveNon-Primitive
StorageStored by valueStored by reference
MutabilityImmutableMutable
MemoryStored in stackStored in heap
ComparisonCompared by valueCompared by reference
Examplesstring, number, booleanobject, array, function


Article 0 of 0