What you’ll learn in this guide:
- JavaScript’s built-in structures: Array, Object, Map, Set, WeakMap, WeakSet
- When to use each built-in structure
- How to implement: Stack, Queue, Linked List, Binary Search Tree
- Choosing the right data structure for the job
- Common interview questions and patterns
What Are Data Structures?
Think of data structures like different ways to organize a library. You could:- Stack books on a table — Easy to add/remove from the top, but finding a specific book means digging through the pile
- Line them up on a shelf — Easy to browse in order, but adding a book in the middle means shifting everything
- Organize by category with an index — Finding any book is fast, but you need to maintain the index
JavaScript’s Built-in Data Structures
JavaScript gives you several data structures out of the box. Let’s look at each one.Arrays
An Array is an ordered collection of values, accessed by numeric index. It’s the most common data structure in JavaScript.| Operation | Method | Complexity | Why |
|---|---|---|---|
| Access by index | arr[i] | O(1) | Direct memory access |
| Add/remove at end | push(), pop() | O(1) | No shifting needed |
| Add/remove at start | unshift(), shift() | O(n) | Must shift all elements |
| Search | indexOf(), includes() | O(n) | Must check each element |
| Insert in middle | splice() | O(n) | Must shift elements after |
- You need ordered data
- You access elements by position
- You mostly add/remove from the end
- You need to iterate over all elements
Objects
An Object stores key-value pairs where keys are strings or Symbols. It’s JavaScript’s fundamental way to group related data.- Keys are converted to strings (numbers become “1”, “2”, etc.)
- Objects have a prototype chain (inherited properties)
- No built-in
.sizeproperty - Property order is preserved in ES2015+, but with specific rules: integer keys are sorted numerically first, then string keys appear in insertion order
- Storing entity data (user profiles, settings)
- When keys are known strings
- Configuration objects
- JSON data
Map
A Map is like an Object but with superpowers: keys can be any type, it maintains insertion order, and has a.size property.
| Feature | Map | Object |
|---|---|---|
| Key types | Any | String or Symbol |
| Order | Guaranteed insertion order | Preserved (integer keys sorted first) |
| Size | map.size | Object.keys(obj).length |
| Iteration | Directly iterable | Need Object.keys() |
| Performance | Better for frequent add/delete | Better for static data |
| Prototype | None | Has prototype chain |
- Keys aren’t strings (objects, functions, etc.)
- You need to know the size frequently
- You add/delete keys often
- Order matters
Set
A Set stores unique values. Duplicates are automatically ignored.These methods are part of ES2024 and are supported in all modern browsers as of late 2024. Check browser compatibility if you need to support older browsers.
- You need unique values
- You check “does this exist?” frequently
- Removing duplicates from arrays
- Tracking visited items
WeakMap and WeakSet
WeakMap and WeakSet (Advanced)
WeakMap and WeakSet (Advanced)
WeakMap and WeakSet are special versions where keys (WeakMap) or values (WeakSet) are held “weakly.” This means they don’t prevent garbage collection.WeakMap:WeakSet:When to use Weak versions:
- Keys must be objects (or non-registered symbols)
- If the key object has no other references, it gets garbage collected
- Not iterable (no
.keys(),.values(),.forEach()) - No
.sizeproperty
- Values must be objects
- Useful for tracking which objects have been processed
- Caching computed data for objects
- Storing private instance data
- Tracking objects without preventing garbage collection
Implementing Common Data Structures
JavaScript doesn’t have built-in Stack, Queue, or Linked List classes, but they’re easy to implement and important to understand.Stack (LIFO)
A Stack follows Last-In-First-Out: the last item added is the first removed. Think of a stack of plates.- Browser history (back button)
- Undo/redo functionality
- Function call stack
- Expression evaluation (parentheses matching)
Queue (FIFO)
A Queue follows First-In-First-Out: the first item added is the first removed. Think of a line at a store.- Task scheduling
- Print queue
- BFS graph traversal
- Message queues
Linked List
A Linked List is a chain of nodes where each node points to the next. Unlike arrays, elements aren’t stored in contiguous memory.| Operation | Array | Linked List |
|---|---|---|
| Access by index | O(1) | O(n) |
| Insert at beginning | O(n) | O(1) |
| Insert at end | O(1) | O(1) with tail pointer |
| Insert in middle | O(n) | O(1) if you have the node |
| Search | O(n) | O(n) |
- Frequent insertions/deletions at the beginning
- You don’t need random access by index
- Implementing queues (for O(1) dequeue)
Binary Search Tree
A Binary Search Tree (BST) is a hierarchical structure where each node has at most two children. The left child is smaller, the right child is larger.| Operation | Average | Worst (unbalanced) |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
- You need fast search, insert, and delete (O(log n) average)
- Data needs to stay sorted
- Implementing autocomplete, spell checkers
Graph
Graph (Brief Overview)
Graph (Brief Overview)
A Graph consists of nodes (vertices) connected by edges. Think social networks (people connected by friendships) or maps (cities connected by roads).Basic Implementation (Adjacency List):Real-world uses:
- Social networks (friend connections)
- Maps and navigation (shortest path)
- Recommendation systems
- Dependency resolution (package managers)
Choosing the Right Data Structure
| Use Case | Best Structure | Why |
|---|---|---|
| Todo list | Array | Ordered, index access |
| User settings | Object | String keys, static |
| Word frequency counter | Map | Easy increment, any key |
| Tag system | Set | Unique values |
| Browser back button | Stack | LIFO |
| Task scheduler | Queue | FIFO |
| Playlist with prev/next | Linked List (doubly) | O(1) traversal |
| Dictionary/autocomplete | Trie | Fast prefix search |
| Social network | Graph | Connections |
Common Interview Questions
Interview questions often test your understanding of data structures. Here are patterns you’ll encounter:Array: Two Sum
Array: Two Sum
Problem: Find two numbers in an array that add up to a target.Approach: Use a Map to store numbers you’ve seen. For each number, check if Why Map? O(1) lookup turns O(n²) brute force into O(n).
target - number exists in the Map.Stack: Valid Parentheses
Stack: Valid Parentheses
Problem: Check if a string of brackets is valid:
()[]{}.Approach: Push opening brackets onto stack. When you see a closing bracket, pop and check if it matches.Linked List: Reverse
Linked List: Reverse
Problem: Reverse a linked list.Approach: Keep track of previous, current, and next. Reverse pointers as you go.Key insight: You need three pointers to avoid losing references.
Linked List: Detect Cycle
Linked List: Detect Cycle
Problem: Determine if a linked list has a cycle.Approach: Floyd’s Tortoise and Hare - use two pointers, one fast (2 steps) and one slow (1 step). If they meet, there’s a cycle.Why this works: In a cycle, the fast pointer will eventually “lap” the slow pointer.
Tree: Maximum Depth
Tree: Maximum Depth
Problem: Find the maximum depth of a binary tree.Approach: Recursively find the depth of left and right subtrees, take the max.Base case: Empty tree has depth 0.
Queue: Implement with Two Stacks
Queue: Implement with Two Stacks
Problem: Implement a queue using only stacks.Approach: Use two stacks. Push to stack1. For dequeue, if stack2 is empty, pour all of stack1 into stack2 (reversing order), then pop from stack2.Amortized O(1): Each element is moved at most twice.
Key Takeaways
The key things to remember:
- Arrays are great for ordered data with index access. Push/pop are O(1), but shift/unshift are O(n).
- Objects store string-keyed data. Use them for static configuration and entity data.
-
Map is the better choice when keys aren’t strings, you need
.size, or you add/delete frequently. -
Set stores unique values. The
[...new Set(arr)]trick removes duplicates instantly. - Stack (LIFO) is perfect for undo/redo, parsing expressions, and DFS traversal.
- Queue (FIFO) is ideal for task scheduling and BFS traversal. Use a linked list for O(1) dequeue.
- Linked Lists excel at insertions/deletions but lack random access. Use when you frequently modify the beginning.
- Binary Search Trees give O(log n) search/insert/delete on average. They keep data sorted.
- Choose based on your most frequent operation. What makes one structure fast makes another slow.
- Interview tip: When you need O(1) lookup, think Map or Set. When you need to track order of operations, think Stack or Queue.
Test Your Knowledge
Question 1: When would you use a Map instead of an Object?
Question 1: When would you use a Map instead of an Object?
Answer:Use Map when:
- Keys are not strings (objects, numbers, etc.)
- You need to know the size frequently (
.sizevsObject.keys().length) - You add/delete keys often (Map is optimized for this)
- You need guaranteed insertion order
- You want to avoid prototype chain issues
- Keys are known strings
- You’re working with JSON data
- You need object destructuring or spread syntax
Question 2: Why is array shift() O(n) but pop() O(1)?
Question 2: Why is array shift() O(n) but pop() O(1)?
Answer:
pop() removes from the end. No other elements need to move.shift() removes from the beginning. Every remaining element must be re-indexed:- Element at index 1 moves to 0
- Element at index 2 moves to 1
- …and so on
Question 3: What's the difference between a Stack and a Queue?
Question 3: What's the difference between a Stack and a Queue?
Answer:Stack (LIFO): Last In, First Out
- Like a stack of plates - you take from the top
push()andpop()operate on the same end- Use for: undo/redo, back button, recursion
- Like a line at a store - first person in line is served first
enqueue()adds to back,dequeue()removes from front- Use for: task scheduling, BFS, print queues
Question 4: When would a Linked List be better than an Array?
Question 4: When would a Linked List be better than an Array?
Answer:Linked List wins when:
- You frequently insert/delete at the beginning (O(1) vs O(n))
- You don’t need random access by index
- You’re implementing a queue (O(1) dequeue)
- Memory is fragmented (nodes can be anywhere)
- You need index-based access
- You iterate sequentially often
- You mostly add/remove from the end
- You need
.length,.map(),.filter(), etc.
Question 5: What makes Binary Search Trees fast?
Question 5: What makes Binary Search Trees fast?
Answer:BSTs use the rule: left < parent < right. This means:
- To find a value, compare with root
- If smaller, go left; if larger, go right
- Each comparison eliminates half the remaining nodes
Question 6: How would you remove duplicates from an array?
Question 6: How would you remove duplicates from an array?
Answer:The cleanest way is with Set:This works because:
new Set(array)creates a Set (which only keeps unique values)[...set]spreads the Set back into an array
Related Concepts
Algorithms & Big O
Understanding time complexity helps you choose the right data structure
Factories & Classes
The class syntax used to implement data structures
Higher-Order Functions
Array methods like map, filter, and reduce
Recursion
Essential for tree and graph traversal algorithms
Reference
Array — MDN
Complete reference for JavaScript arrays
Object — MDN
Documentation for Object methods and properties
Map — MDN
Guide to the Map collection type
Set — MDN
Documentation for Set and its new ES2024 methods
WeakMap — MDN
When to use WeakMap for memory management
Data Structures Guide — MDN
MDN’s overview of JavaScript data types and structures
Articles
Map and Set — JavaScript.info
The clearest explanation of Map and Set with interactive examples. Covers WeakMap and WeakSet too.
JavaScript Algorithms and Data Structures
Oleksii Trekhleb’s legendary GitHub repo with implementations of every data structure and algorithm in JavaScript. Over 180k stars for good reason.
Data Structures in JavaScript
freeCodeCamp’s practical guide covering arrays through graphs with real-world examples you can follow along with.
Itsy Bitsy Data Structures
Jamie Kyle’s annotated source code explaining data structures in ~200 lines. Perfect if you learn by reading well-commented code.
Videos
Data Structures and Algorithms in JavaScript
freeCodeCamp’s complete 8-hour course covering everything from Big O to graph algorithms. Great for interview prep.
JavaScript Data Structures: Getting Started
Academind’s beginner-friendly introduction focusing on when and why to use each structure, not just how.
Data Structures Easy to Advanced
William Fiset’s comprehensive course with animations that make complex structures like trees and graphs click.