# 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

```javascript
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)<br>
* **Search (has):** O(1) (Constant time - the magic of hashing)

#### Comprehensive Operations Guide

```javascript
const ids = new Set([101, 102]);

// --- 1. ADD & REMOVE ---
ids.add(103);           // Add item
ids.add(101);           // Ignored! (Duplicate)
ids.delete(102);        // Remove item -> Returns true if found
ids.clear();            // Wipes entire set O(1)

// --- 2. CHECKS & PROPERTIES ---
console.log(ids.size);  // Count items (Not .length!)
if (ids.has(103)) {     // Fast O(1) lookup
    console.log('Found it');
}

// --- 3. ITERATION ---
// Sets preserve insertion order
for (const id of ids) {
    console.log(id);
}
ids.forEach(value => console.log(value));

// --- 4. SET MATH (Common Patterns) ---
const setA = new Set([1, 2, 3]);
const setB = new Set([3, 4, 5]);

// Union (Combine all)
const union = new Set([...setA, ...setB]); // {1, 2, 3, 4, 5}

// Intersection (Common items)
const intersection = new Set([...setA].filter(x => setB.has(x))); // {3}

```

> **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

```javascript
const userCache = new Map();
const configObj = { id: 1 };

// --- 1. SETTING & GETTING ---
userCache.set('admin', 'Alice');      // String key
userCache.set(configObj, 'Settings'); // Object key!
userCache.set('admin', 'Bob');        // Overwrites 'Alice'

const val = userCache.get(configObj); // 'Settings'
const missing = userCache.get('guest'); // undefined

// --- 2. DELETING & CHECKING ---
userCache.delete('admin');   // Returns true if deleted
const hasConfig = userCache.has(configObj); // true
userCache.clear();           // Empty the map

// --- 3. ITERATION VARIATIONS ---
// A. Iterate Pairs (Default)
for (const [key, value] of userCache) {
    console.log(`${key} => ${value}`);
}

// B. Iterate Keys Only
for (const key of userCache.keys()) {
    console.log(key);
}

// C. Iterate Values Only
for (const val of userCache.values()) {
    console.log(val);
}

// --- 4. CONVERSION ---
// Convert to Array of pairs
const mapAsArray = [...userCache]; // [[{id:1}, 'Settings']]

```

> **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** | <p>Slow O(n)<br></p>  | <p><strong>Fast</strong> O(1)<br></p> | <p><strong>Fast</strong> O(1)<br></p> |
| **Use Case**     | Lists, Stacks, Queues | Uniqueness, Fast Checks               | Caches, Dictionaries                  |
