๐Ÿงฌ JavaScript Advanced Data Types
Estimated reading: 6 minutes 10 views

JavaScript Arrays, Sets, Maps, WeakMap, WeakSet & Typed Arrays: Complete Guide

In JavaScript, data structures play a vital role in efficiently managing and organizing data. Arrays, Sets, Maps, Typed Arrays, WeakMaps, and WeakSets are foundational structures that developers use to handle collections of data. Each data structure has its unique properties, strengths, and use cases, making it essential to understand when and how to use them.

This guide will explore each of these data structures in detail, with practical examples and usage tips, helping both beginners and experienced developers leverage them effectively.


๐Ÿ“Œ 1. JavaScript Arrays

Arrays in JavaScript are one of the most commonly used data structures for storing ordered collections of items. An array can store multiple values, including numbers, strings, objects, and even other arrays.

Key Features:

  • Arrays are ordered, meaning the position of each element is important.
  • They can contain heterogeneous data types (e.g., strings, numbers, objects).
  • Arrays are zero-indexed, meaning the first element is at index 0.

Array Methods:

  • push(): Adds an element to the end of the array.
  • pop(): Removes the last element from the array.
  • shift(): Removes the first element.
  • unshift(): Adds an element to the beginning.
  • map(), filter(), reduce(): Functional programming methods for transformations.

Example:

let arr = [1, 'apple', true, [1, 2]];  // Array with mixed types
arr.push(42); // Adds 42 at the end
console.log(arr); // [1, 'apple', true, [1, 2], 42]

๐Ÿ“˜ Line-by-Line Breakdown:

  • let arr = [...]: Initializes an array with different types of data.
  • arr.push(42): Adds the number 42 to the array.

๐Ÿ“Œ 2. JavaScript Sets

A Set is a collection of unique values. It ensures that each value in the set is distinct. Sets do not maintain an order (in terms of indexing), and values are automatically removed if they are duplicated.

Key Features:

  • A Set only stores unique values.
  • Sets are unordered collections.
  • Provides methods like .add(), .delete(), .has(), and .clear().

Example:

let set = new Set([1, 2, 3, 3, 4, 5]);
set.add(6); // Adds 6 to the set
console.log(set); // Set { 1, 2, 3, 4, 5, 6 }

๐Ÿ“˜ Line-by-Line Breakdown:

  • let set = new Set([...]): Creates a Set from an array, automatically removing duplicates.
  • set.add(6): Adds 6 to the set, ensuring no duplicates.

๐Ÿ“Œ 3. JavaScript Maps

A Map is a collection of key-value pairs. Unlike objects, maps can have keys of any data type, not just strings or symbols. Maps also maintain the order of elements.

Key Features:

  • Maps store key-value pairs where keys can be any data type.
  • The insertion order of keys is maintained.
  • Common methods: .set(), .get(), .has(), .delete().

Example:

let map = new Map();
map.set('name', 'Alice');
map.set('age', 25);
console.log(map.get('name')); // 'Alice'

๐Ÿ“˜ Line-by-Line Breakdown:

  • let map = new Map(): Initializes an empty map.
  • map.set('name', 'Alice'): Sets a key-value pair.
  • map.get('name'): Retrieves the value associated with the key 'name'.

๐Ÿ“Œ 4. JavaScript Typed Arrays

Typed Arrays are array-like objects that provide a mechanism for accessing raw binary data. They are particularly useful when working with binary data in web APIs or for performance-sensitive applications.

Key Features:

  • Typed Arrays provide a way to handle binary data efficiently.
  • They are specialized arrays, such as Uint8Array, Int32Array, Float64Array, etc.
  • They offer a view of binary data from an ArrayBuffer.

Example:

let buffer = new ArrayBuffer(16);  // 16-byte buffer
let view = new Int32Array(buffer); // Create a view of the buffer as 32-bit integers
view[1] = 42; // Assign value to the second element
console.log(view); // Int32Array(4) [ 0, 42, 0, 0 ]

๐Ÿ“˜ Line-by-Line Breakdown:

  • let buffer = new ArrayBuffer(16): Creates a buffer with 16 bytes of raw data.
  • let view = new Int32Array(buffer): Views the buffer as an array of 32-bit integers.
  • view[1] = 42: Sets the second element to 42.

๐Ÿ“Œ 5. JavaScript WeakMap

A WeakMap is similar to a Map but with a key difference: the keys of a WeakMap are weakly referenced, meaning if there are no other references to the key object, the key-value pair can be garbage collected. This is useful for managing memory in cases where objects are temporary.

Key Features:

  • Keys must be objects (not primitive values).
  • Weak references allow for automatic garbage collection.
  • Common methods: .set(), .get(), .has(), .delete().

Example:

let obj = {};
let weakMap = new WeakMap();
weakMap.set(obj, 'value');
console.log(weakMap.get(obj)); // 'value'

๐Ÿ“˜ Line-by-Line Breakdown:

  • let obj = {}: Initializes an object.
  • let weakMap = new WeakMap(): Creates a new WeakMap.
  • weakMap.set(obj, 'value'): Sets a key-value pair where the key is an object.

๐Ÿ“Œ 6. JavaScript WeakSet

A WeakSet is a collection of objects where each object can only appear once, and the objects are weakly referenced. Like a WeakMap, objects in a WeakSet can be garbage collected when there are no other references to them.

Key Features:

  • Only objects can be stored in a WeakSet.
  • Objects are weakly referenced.
  • Methods include .add(), .delete(), and .has().

Example:

let obj1 = {};
let obj2 = {};
let weakSet = new WeakSet();
weakSet.add(obj1);
console.log(weakSet.has(obj1)); // true
weakSet.delete(obj1);
console.log(weakSet.has(obj1)); // false

๐Ÿ“˜ Line-by-Line Breakdown:

  • let obj1 = {};: Creates an object.
  • let weakSet = new WeakSet(): Initializes a new WeakSet.
  • weakSet.add(obj1): Adds the object to the WeakSet.
  • weakSet.delete(obj1): Deletes the object from the WeakSet.

โšก Performance Considerations & Best Practices

  • Arrays: When dealing with large collections of data that require frequent mutations, consider using Typed Arrays for better performance.
  • Sets and Maps: Use Sets for uniqueness and Maps for key-value associations. Maps are especially useful when you need to associate a key with any type of value.
  • WeakMap/WeakSet: These are ideal for situations where you need to store temporary data without preventing garbage collection of unused objects.

๐Ÿ“Œ Summary

In this guide, we covered the core JavaScript data structures: Arrays, Sets, Maps, Typed Arrays, WeakMap, and WeakSet. Each structure serves specific purposes and has unique properties that make them suitable for different scenarios.

  • Use Arrays for ordered collections and Sets for ensuring uniqueness.
  • Maps are great for key-value pairs where keys can be any type.
  • Typed Arrays are essential for performance-sensitive applications handling binary data.
  • WeakMap and WeakSet are specialized collections that allow for automatic garbage collection of objects.

Understanding when and how to use these data structures can significantly improve the efficiency and maintainability of your JavaScript code.


โ“ FAQ Section

โ“ When should I use a Set over an Array in JavaScript?

Use a Set when you need to store only unique values and donโ€™t care about the order of insertion. Sets automatically remove duplicates.

โ“ What is the difference between a Map and an Object in JavaScript?

While both Map and Object store key-value pairs, Map allows any data type for keys and maintains the order of insertion, while Objects only allow strings or symbols as keys.

โ“ What are the use cases for WeakMap and WeakSet?

WeakMap is useful for managing private data or caching, where you donโ€™t want the references to prevent garbage collection. WeakSet is ideal for tracking a collection of objects without keeping them alive unnecessarily.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

JavaScript โ€” Arrays / Sets / Maps / Typed Arrays / WeakMap / WeakSet

Or Copy Link

CONTENTS
Scroll to Top