DEV Community

Cover image for Understanding JavaScript Collections: Arrays, Sets, Maps, and More
EneasLari
EneasLari

Posted on • Originally published at eneaslari.com

Understanding JavaScript Collections: Arrays, Sets, Maps, and More

JavaScript provides developers with a variety of built-in collection types that allow for flexible and efficient data storage and manipulation. In this article, we'll explore the most commonly used collections, like arrays, sets, and maps, and learn how to use them with descriptive examples.

1. Arrays

Arrays are one of the most commonly used data structures in JavaScript. They allow you to store a list of items (which can be of any type) in a sequential manner.

Creating an Array:

let fruits = ["apple", "banana", "cherry"];
Enter fullscreen mode Exit fullscreen mode

Accessing an Array:

console.log(fruits[0]); // Outputs: apple
Enter fullscreen mode Exit fullscreen mode

Adding and Removing Items:

fruits.push("orange"); // Adds "orange" to the end
fruits.pop(); // Removes the last item ("orange")
Enter fullscreen mode Exit fullscreen mode

2. Sets

A Set is a unique collection of values. This means that the same value cannot appear more than once.

Creating a Set:

let uniqueNumbers = new Set([1, 2, 3, 3, 4]);
Enter fullscreen mode Exit fullscreen mode

Note that even though the number 3 appears twice in the list, the Set will only store it once.

Adding and Removing Items:

uniqueNumbers.add(5); // Adds 5 to the set
uniqueNumbers.delete(2); // Removes 2 from the set
Enter fullscreen mode Exit fullscreen mode

3. Maps

Maps, also known as dictionaries or associative arrays in other languages, are collections of key-value pairs.

Creating a Map:

let capitals = new Map([
  ["France", "Paris"],
  ["Spain", "Madrid"],
  ["Germany", "Berlin"]
]);
Enter fullscreen mode Exit fullscreen mode

Accessing Values by Keys:

console.log(capitals.get("France")); // Outputs: Paris
Enter fullscreen mode Exit fullscreen mode

Adding and Removing Key-Value Pairs:

capitals.set("Italy", "Rome"); // Adds key-value pair ["Italy", "Rome"]
capitals.delete("Germany"); // Removes key-value pair for "Germany"
Enter fullscreen mode Exit fullscreen mode

4. Typed Arrays

Typed Arrays are a special type of array that allows you to store a sequence of numbers in a much more memory-efficient way than regular arrays. They come in various types depending on the precision and type of number (e.g., Int8Array, Float32Array).

Creating a Typed Array:

let numbers = new Int16Array([1, 2, 3, 4, 5]);
Enter fullscreen mode Exit fullscreen mode

Typed arrays are especially useful when working with WebGL or WebAudio APIs, as they allow for better performance.

5. WeakSet and WeakMap

Both WeakSet and WeakMap are collections where the items (or keys, in the case of WeakMap) are held "weakly", meaning that if there are no other references to the item (or key), it can be garbage collected. This is useful for maintaining relationships between objects without preventing those objects from being garbage collected when they're no longer needed.

Example using WeakMap:

let obj = { key: "value" };
let weakmap = new WeakMap();

weakmap.set(obj, "This is the object's associated value");

// When obj is set to null, the entry in the WeakMap will be garbage collected
obj = null;
Enter fullscreen mode Exit fullscreen mode

Conclusion

JavaScript offers a range of collections to cater to different use-cases. Whether you're storing a list of items in sequence with arrays, ensuring unique values with sets, or associating keys with values using maps, JavaScript provides the tools you need for efficient data storage and manipulation. As with all tools, the key is to understand when and how to use them effectively in your code.

Bonus

The collection types the article provided was a concise overview of some of the most commonly used collections in JavaScript. However, there are more nuances and other types of collections and related utilities in JavaScript. Let's expand on that a bit:

1. Array-Like Objects

While arrays are the primary sequence data structure in JavaScript, there are also array-like objects such as:

  • arguments: This is an array-like object accessible inside functions that represents the passed arguments.
   function showArguments() {
      console.log(arguments[0]);
   }

   showArguments("hello", "world");  // Outputs: hello
Enter fullscreen mode Exit fullscreen mode
  • NodeList: When you use methods like document.querySelectorAll(), it returns a NodeList which is array-like.
   const divs = document.querySelectorAll('div');
   console.log(divs[0]);  // Outputs the first div element
Enter fullscreen mode Exit fullscreen mode

2. Object

While not exactly a collection in the traditional sense, JavaScript's core object type (Object) is a collection of key-value pairs.

let person = {
   name: "John",
   age: 30
};

console.log(person.name);  // Outputs: John
Enter fullscreen mode Exit fullscreen mode

3. String

Strings in JavaScript can be thought of as collections (or sequences) of characters.

let greeting = "hello";
console.log(greeting[0]);  // Outputs: h
Enter fullscreen mode Exit fullscreen mode

4. WeakRef

Introduced in ECMAScript 2021 (ES12), WeakRef provides a way to hold a weak reference to an object, which doesn't prevent the object from being garbage collected.

let obj = { data: "important data" };
let weakRef = new WeakRef(obj);

// The object referred to by weakRef can still be garbage collected.
Enter fullscreen mode Exit fullscreen mode

5. Others

There are other advanced or specialized collections and data handling utilities:

  • BigInt64Array and BigUint64Array: Typed arrays to handle big integers.
  • DataView: Provides a low-level interface for reading and writing multiple number types in an ArrayBuffer without being tied to a specific bit-length representation.
  • ArrayBuffer: Represents a generic, fixed-length raw binary data buffer. Often used in conjunction with data views (DataView) and typed arrays.

Top comments (0)