JavaScript collections are data structures used to store, organize, retrieve, and manipulate groups of values. Choosing the right collection can make your code simpler, faster, and easier to maintain.

Learn software engineering

The most important JavaScript collections are:

  • Arrays
  • Objects
  • Map
  • Set
  • WeakMap
  • WeakSet

1. Arrays

An Array is an ordered collection of values. Each value has a numeric index beginning at 0.

const languages = ["JavaScript", "Python", "Java"];

console.log(languages[0]);
// JavaScript

Arrays can contain almost anything:

const data = [
  "JavaScript",
  42,
  true,
  { framework: "React" },
  ["Node.js", "Express"]
];

Common Array operations

const fruits = ["Apple", "Banana"];

fruits.push("Orange");    // Add to end
fruits.unshift("Mango"); // Add to beginning

fruits.pop();             // Remove from end
fruits.shift();           // Remove from beginning

Arrays also provide powerful transformation methods.

const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(n => n * 2);

const even = numbers.filter(n => n % 2 === 0);

const total = numbers.reduce(
  (sum, n) => sum + n,
  0
);

console.log(doubled);
// [2, 4, 6, 8, 10]

console.log(even);
// [2, 4]

console.log(total);
// 15

Use an Array when order and position matter.

2. Objects

Objects store information as key-value pairs.

const developer = {
  name: "Alex",
  language: "JavaScript",
  experience: 5
};

Access properties using dot notation:

console.log(developer.name);

Or bracket notation:

console.log(developer["language"]);

You can add or modify properties:

developer.framework = "React";

developer.experience = 6;

And remove them:

delete developer.framework;

Objects are especially useful for representing structured entities:

const product = {
  id: 101,
  name: "Laptop",
  price: 1500,
  inStock: true
};

Objects aren’t technically part of JavaScript’s specialized keyed-collection types, but they are one of the language’s most commonly used structures for storing collections of named values.

3. Map

A Map stores key-value pairs, similar to an Object.

const user = new Map();

user.set("name", "Alex");
user.set("role", "Developer");
user.set("age", 30);

console.log(user.get("name"));
// Alex

The major difference is that Map keys can be any value, not just strings or symbols.

const map = new Map();

map.set("name", "JavaScript");
map.set(10, "Ten");
map.set(true, "Boolean");

const obj = {};

map.set(obj, "Object key");

Useful Map methods

const languages = new Map();

languages.set("js", "JavaScript");
languages.set("py", "Python");
languages.set("java", "Java");

languages.get("js");
// JavaScript

languages.has("py");
// true

languages.delete("java");

console.log(languages.size);
// 2

Clear everything:

languages.clear();

Iterating through a Map

const frameworks = new Map([
  ["React", "Frontend"],
  ["Express", "Backend"],
  ["Next.js", "Full Stack"]
]);

for (const [name, type] of frameworks) {
  console.log(name, type);
}

You can also retrieve keys and values separately:

frameworks.keys();
frameworks.values();
frameworks.entries();

Use Map when you need a true key-value collection, particularly when keys aren’t necessarily strings.

4. Set

A Set stores unique values.

const numbers = new Set();

numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(20);

console.log(numbers);
// Set(3) {10, 20, 30}

The second 20 isn’t added because Sets don’t contain duplicate values.

Common Set operations

const technologies = new Set([
  "JavaScript",
  "React",
  "Node.js"
]);

technologies.add("TypeScript");

technologies.has("React");
// true

technologies.delete("Node.js");

console.log(technologies.size);

Removing duplicates with Set

One of the most useful applications of Set is removing duplicate array values.

const numbers = [1, 2, 2, 3, 3, 4, 5];

const unique = [...new Set(numbers)];

console.log(unique);
// [1, 2, 3, 4, 5]

Iterating through Sets

const skills = new Set([
  "JavaScript",
  "React",
  "Node.js"
]);

for (const skill of skills) {
  console.log(skill);
}

Use a Set when uniqueness matters.

5. Set Operations

Modern JavaScript also supports useful mathematical-style Set operations in current runtimes.

Suppose we have:

const frontend = new Set([
  "JavaScript",
  "React",
  "CSS"
]);

const backend = new Set([
  "JavaScript",
  "Node.js",
  "SQL"
]);

Union

Everything contained in either Set:

const allSkills = frontend.union(backend);

Result conceptually:

JavaScript
React
CSS
Node.js
SQL

Intersection

Values appearing in both:

const shared = frontend.intersection(backend);

Result:

JavaScript

Difference

Values in one Set but not the other:

const frontendOnly =
  frontend.difference(backend);

Result:

React
CSS

There are also methods such as:

setA.isSubsetOf(setB);
setA.isSupersetOf(setB);
setA.isDisjointFrom(setB);
setA.symmetricDifference(setB);

These are particularly useful when JavaScript Sets represent permissions, categories, selections, tags, or groups.

6. WeakMap

WeakMap is similar to Map, but its keys must be objects or non-registered symbols.

const privateData = new WeakMap();

const user = {
  name: "Alex"
};

privateData.set(user, {
  password: "secret"
});

console.log(privateData.get(user));

One important property of WeakMap is that it doesn’t keep an object alive solely because that object exists as a key.

For example:

let user = {
  name: "Alex"
};

const metadata = new WeakMap();

metadata.set(user, {
  lastLogin: Date.now()
});

user = null;

If nothing else references the original object, JavaScript is free to garbage-collect it.

This makes WeakMaps useful for associating metadata or private information with objects without unnecessarily preventing garbage collection.

Unlike Map, WeakMap isn’t enumerable.

You can’t do this:

for (const item of metadata) {
  // TypeError
}

Nor does it expose a size property.

7. WeakSet

WeakSet follows a similar idea but stores unique garbage-collectable values, such as objects and non-registered symbols, rather than key-value pairs.

const processedUsers = new WeakSet();

const user = {
  name: "Alex"
};

processedUsers.add(user);

console.log(
  processedUsers.has(user)
);
// true

A useful pattern is keeping track of objects that have already been processed:

const visited = new WeakSet();

function processUser(user) {

  if (visited.has(user)) {
    return;
  }

  visited.add(user);

  console.log("Processing...");
}

Like WeakMap, WeakSet isn’t enumerable.

Array vs Object vs Map vs Set

CollectionStructureDuplicatesTypical use
ArrayIndexed valuesYesOrdered lists
ObjectPropertiesKeys uniqueStructured records
MapKey-value pairsKeys uniqueDynamic dictionaries
SetValuesNoUnique values
WeakMapWeak key-value associationsKeys uniqueObject metadata
WeakSetWeak collection of valuesNoTracking objects

The easiest way to remember the distinction is:

Need an ordered list?
        ↓
      Array

Need a structured record?
        ↓
      Object

Need key → value relationships?
        ↓
       Map

Need unique values?
        ↓
       Set

Need object-associated data
without preventing garbage collection?
        ↓
     WeakMap

Need to weakly track whether
an object belongs to a group?
        ↓
     WeakSet

Practical Example

Consider an application managing students.

An Array can hold the students:

const students = [
  { id: 1, name: "John" },
  { id: 2, name: "Sarah" }
];

A Map can provide fast lookup by ID:

const studentMap = new Map();

for (const student of students) {
  studentMap.set(student.id, student);
}

console.log(studentMap.get(2));
// { id: 2, name: "Sarah" }

A Set can track unique courses:

const courses = new Set([
  "JavaScript",
  "Python",
  "JavaScript",
  "React"
]);

console.log(courses);
// JavaScript, Python, React

And a WeakMap can associate internal metadata with each student object:

const metadata = new WeakMap();

metadata.set(students[0], {
  lastViewed: Date.now()
});

The key idea is that JavaScript doesn’t have one universal collection for every problem. Arrays organize ordered data, Objects model structured records, Maps manage flexible key-value relationships, Sets enforce uniqueness, and WeakMaps/WeakSets provide object-oriented associations with garbage-collection-friendly behavior. That’s how JavaScript collections work.

codeflare

Latest tech news and coding tips.

Share
Published by
codeflare

Recent Posts

Backpressure in Node.js

Backpressure is a flow-control mechanism that prevents a fast data producer from overwhelming a slower data…

2 hours ago

Context Poisoning Explained

Context poisoning is a technique where an attacker deliberately places misleading, malicious, or irrelevant information into…

4 days ago

Common React Errors

React makes building user interfaces easier, but certain errors appear repeatedly, especially when working with…

2 weeks ago

C Programming Cheat Sheet

The C programming language is a foundational, general-purpose computer programming language created by Dennis Ritchie at Bell Labs in 1972. Originally developed to…

2 weeks ago

Homebrew Tutorial

What Is Homebrew? Homebrew is a package manager for macOS and Linux that makes it easy to…

3 weeks ago

10 Ways to Loop Through a JavaScript Array

JavaScript gives you several ways to iterate over an array. Some are better for simple…

3 weeks ago