DEV Community

Usool
Usool

Posted on

JavaScript Data Structures Cheat Sheet: Arrays, Typed Arrays, Sets, Maps, and WeakMaps (with Python Equivalents)

Suppose you are a full-stack dev and know your way around the Python and JavaScriipt ecosystem. In that case, you should understand that Python and JavaScript’s core data structures are crucial for writing efficient code. Many of these structures have close parallels in both ecosystems which makes the transition easier. In this post, we’ll explore JavaScript's Arrays, Typed Arrays, Sets, Maps, and WeakMaps, alongside their Python equivalents, with examples in both languages to highlight the similarities and differences.


1. Arrays

JavaScript arrays are ordered, mutable collections that can hold any data type.

Key Concepts:

  • Mutability: Arrays are mutable.
  • Common Methods:
    • Push/Pop: Adds/removes elements at the end (push()/pop()).
    • Shift/Unshift: Adds/removes elements at the beginning (shift()/unshift()).
    • Map/Filter/Reduce: map(), filter(), and reduce() for transformations and aggregations.
  • When to Use: Use arrays when you need to store a list of elements, with quick access and operations like sorting or filtering.

JavaScript Example:

let numbers = [1, 2, 3, 4];
let squares = numbers.map(x => x * x);  // [1, 4, 9, 16]
Enter fullscreen mode Exit fullscreen mode

Python Example:

numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))  # [1, 4, 9, 16]
Enter fullscreen mode Exit fullscreen mode

Use Case: Maintaining a list of user inputs or performing bulk operations like sorting.


2. Typed Arrays

Typed arrays allow efficient handling of binary data in JavaScript.

Key Concepts:

  • Memory Efficiency: Use for handling raw binary data in specific formats (e.g., Int8Array, Float32Array).
  • ArrayBuffer: Holds the raw binary data, which is accessed via typed arrays.
  • When to Use: Use when performance is critical, such as in scientific computing, graphics, or Web APIs like WebGL.

JavaScript Example:

let buffer = new ArrayBuffer(16);  // 16 bytes buffer
let intView = new Int32Array(buffer);
intView[0] = 42;
Enter fullscreen mode Exit fullscreen mode

Python Example (using numpy):

import numpy as np
int_array = np.array([42], dtype=np.int32)  # array with 32-bit integer
Enter fullscreen mode Exit fullscreen mode

Use Case: Processing large numeric datasets efficiently, such as audio or image data.


3. Set Data Structure

A Set stores unique values with no duplicates and provides fast lookups.

Key Concepts:

  • Uniqueness: Values must be unique.
  • Methods:
    • add(), delete(), clear() for manipulation.
    • has() to check for membership.
    • forEach() for iteration.
  • When to Use: Use Set when you need a collection of unique values or to remove duplicates.

JavaScript Example:

let uniqueNumbers = new Set([1, 2, 3, 3, 4]);  // Set {1, 2, 3, 4}
uniqueNumbers.add(5);  // Set {1, 2, 3, 4, 5}
Enter fullscreen mode Exit fullscreen mode

Python Example:

unique_numbers = set([1, 2, 3, 3, 4])  # {1, 2, 3, 4}
unique_numbers.add(5)  # {1, 2, 3, 4, 5}
Enter fullscreen mode Exit fullscreen mode

Use Case: Storing unique user IDs or removing duplicates from a list.


4. Map Data Structure

A Map stores key-value pairs, where keys can be of any type (not limited to strings).

Key Concepts:

  • Any Type Keys: Keys can be any data type, including objects.
  • Methods:
    • set(), get(), delete(), and has() for managing key-value pairs.
    • forEach(), entries(), keys(), and values() for iteration.
  • When to Use: Use a Map when you need a dictionary-like structure with non-string keys or ordered iteration.

JavaScript Example:

let userRoles = new Map();
userRoles.set('Alice', 'Admin');
userRoles.set(123, 'User');
console.log(userRoles.get(123));  // "User"
Enter fullscreen mode Exit fullscreen mode

Python Example:

user_roles = {'Alice': 'Admin', 123: 'User'}
print(user_roles[123])  # "User"
Enter fullscreen mode Exit fullscreen mode

Use Case: Storing configurations or caching data with keys that are objects or non-string values.


5. WeakMap

A WeakMap is like a Map, but its keys are objects that are weakly referenced, meaning the key-value pair is garbage collected if the key object is no longer referenced.

Key Concepts:

  • Garbage Collection: If the key (an object) is no longer referenced elsewhere, it is garbage collected.
  • No Iteration: WeakMaps do not support iteration or size checks.
  • When to Use: Use WeakMap when you need to associate data with an object while allowing for memory-efficient garbage collection.

JavaScript Example:

let weakMap = new WeakMap();
let obj = {};
weakMap.set(obj, 'Metadata');
Enter fullscreen mode Exit fullscreen mode

Python Example (using weakref.WeakKeyDictionary):

import weakref
class MyClass:
    pass

obj = MyClass()
weak_map = weakref.WeakKeyDictionary()
weak_map[obj] = 'Metadata'
Enter fullscreen mode Exit fullscreen mode

Use Case: Storing metadata for objects, such as DOM nodes in a browser, without preventing garbage collection.


Comparison Table:

JavaScript Python
Array list
TypedArray array, numpy.array
Set set
Map dict
WeakMap weakref.WeakKeyDictionary

When to Use Each Data Structure:

  • Array: When you need an ordered list with quick access by index.
  • TypedArray: When you need efficient storage and manipulation of binary data.
  • Set: When you need a collection of unique values and fast lookups.
  • Map: When you need a key-value store with keys of any type.
  • WeakMap: When managing memory efficiently is critical, and keys should not prevent garbage collection.

I would like to reiterate that mastering these data structures gives you more control over how your code handles data. Whether you’re optimizing performance with Typed Arrays, ensuring unique values with Sets, or managing object metadata with WeakMaps, each structure has a specific purpose. For Python developers, understanding these structures is made easier by their close parallels in the Python ecosystem.

Top comments (0)