JS Data Structures

Knowing the difference between them is often the difference between O(n) code that hangs the browser and O(1) code that runs instantly.

1. Arrays: The Ordered Workhorse

Arrays are the oldest and most versatile structure in JS. They are ordered lists indexed by integers.

When to use them

  • Order matters (e.g., a timeline of events).

  • You need to access elements by index (arr[5]).

  • You are doing heavy transformation (mapping/filtering).

Performance Profile

  • Access/Read: O(1) (Instant)

  • Push/Pop (End): O(1) (Fast)

  • Shift/Unshift (Start): O(n) (Slow - requires re-indexing every element)

  • Search (indexOf/includes): O(n) (Linear scan)

Comprehensive Operations Guide

const stack = ['Node', 'React', 'Vue'];

// --- 1. ADDING ITEMS ---
stack.push('Svelte');       // Add to End (Fast) -> Returns new length
stack.unshift('Angular');   // Add to Start (Slow) -> Returns new length
stack.splice(1, 0, 'Bun');  // Add to Middle (Slow) -> Insert at index 1

// --- 2. REMOVING ITEMS ---
const last = stack.pop();        // Remove End -> Returns item
const first = stack.shift();     // Remove Start -> Returns item
stack.splice(2, 1);              // Remove 1 item at index 2

// --- 3. ACCESSING & FINDING ---
const item = stack[1];           // Standard access by index
const lastItem = stack.at(-1);   // Modern way to get last item (ES2022)
const index = stack.indexOf('React'); // Find index (-1 if missing)
const hasIt = stack.includes('Vue');  // Boolean check (true/false)

// --- 4. ITERATION ---
// A. Standard Loop (Readable, supports 'break/continue')
for (const item of stack) {
    console.log(item);
}

// B. Functional Loop (Cannot break, gives index)
stack.forEach((item, index) => {
    console.log(`${index}: ${item}`);
});

// C. Transformation (Returns new array)
const upperStack = stack.map(tech => tech.toUpperCase());

Expert Insight: Avoid shift() inside large loops. It forces the engine to move every remaining item in memory one slot to the left. If you need a queue, consider a linked list implementation or simply using pointers.

2. Sets: The Unique Guard

Introduced in ES6 (2015), a Set is a collection of unique values. It does not allow duplicates.

When to use them

  • Deduplication: Removing duplicate items from an array.

  • High-Performance Lookups: Checking if an item exists (has()) is significantly faster than Array includes().

Performance Profile

  • Add/Delete: O(1)

  • Search (has): O(1) (Constant time - the magic of hashing)

Comprehensive Operations Guide

Expert Insight: Objects are stored by reference. set.add({a:1}) and set.add({a:1}) will create two entries because they are different objects in memory.

3. Maps: The Dictionary Powerhouse

Before ES6, we used Objects as dictionaries. Map solves the limitations of Objects (keys limited to strings, no size property, prototype pollution).

When to use them

  • Non-String Keys: You need to map a DOM node, an object, or a function to a value.

  • Frequent Additions/Removals: Maps are optimized for this scenario better than Objects.

  • Order Preservation: Maps iterate in insertion order (unlike Objects which have complex sorting rules).

Performance Profile

  • Set/Get/Delete: O(1) on average.

Comprehensive Operations Guide

Expert Insight - The WeakMap: If you are building a framework or library, look into WeakMap. It holds "weak" references to keys, meaning if the key object is deleted elsewhere in your code, the entry in the Map is automatically garbage collected. This prevents memory leaks.

Summary: The Selection Cheat Sheet

Feature

Array []

Set new Set()

Map new Map()

Duplicates

Allowed

Forbidden

Keys unique, Values repeat

Key Types

Indices (0, 1...)

N/A

Any Type

Lookup Speed

Slow O(n)

Fast O(1)

Fast O(1)

Use Case

Lists, Stacks, Queues

Uniqueness, Fast Checks

Caches, Dictionaries

Last updated