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.
The most important JavaScript collections are:
MapSetWeakMapWeakSetAn 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"]
]; 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.
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.
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"); 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(); 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.
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.
const technologies = new Set([
"JavaScript",
"React",
"Node.js"
]);
technologies.add("TypeScript");
technologies.has("React");
// true
technologies.delete("Node.js");
console.log(technologies.size); 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] const skills = new Set([
"JavaScript",
"React",
"Node.js"
]);
for (const skill of skills) {
console.log(skill);
} Use a Set when uniqueness matters.
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"
]); Everything contained in either Set:
const allSkills = frontend.union(backend); Result conceptually:
JavaScript
React
CSS
Node.js
SQL Values appearing in both:
const shared = frontend.intersection(backend); Result:
JavaScript 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.
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.
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.
| Collection | Structure | Duplicates | Typical use |
|---|---|---|---|
Array | Indexed values | Yes | Ordered lists |
Object | Properties | Keys unique | Structured records |
Map | Key-value pairs | Keys unique | Dynamic dictionaries |
Set | Values | No | Unique values |
WeakMap | Weak key-value associations | Keys unique | Object metadata |
WeakSet | Weak collection of values | No | Tracking 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 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.
Backpressure is a flow-control mechanism that prevents a fast data producer from overwhelming a slower data…
Context poisoning is a technique where an attacker deliberately places misleading, malicious, or irrelevant information into…
React makes building user interfaces easier, but certain errors appear repeatedly, especially when working with…
The C programming language is a foundational, general-purpose computer programming language created by Dennis Ritchie at Bell Labs in 1972. Originally developed to…
What Is Homebrew? Homebrew is a package manager for macOS and Linux that makes it easy to…
JavaScript gives you several ways to iterate over an array. Some are better for simple…