javascript-today

Set, Map, Arrays, Objects

Set, Map, Arrays, Objects

what I will be covering in this article

  • What is the difference.
  • When to use what.

What is the difference

JavaScript gives you four main ways to group data together: Arrays, Objects, Maps, and Sets. They overlap a lot, which is exactly why it can be confusing to pick between them. Here is what actually separates them.

Arrays – an ordered list of values, accessed by numeric index. Great for anything where order matters or where you are dealing with a sequence of similar items.

let fruits = ["apple", "banana", "cherry"];
fruits[0]; // "apple"

Objects – a collection of key/value pairs where keys are strings (or Symbols). Great for representing a single “thing” with named properties.

let user = { name: "Sam", age: 30 };
user.name; // "Sam"

Maps – like an Object, but keys can be any type (objects, functions, numbers, etc.), the order of insertion is always preserved, and it comes with a built in .size instead of having to count keys yourself. See the Map data structures article for the full method list.

let scores = new Map();
scores.set("sam", 10);
scores.get("sam"); // 10

Sets – a collection of unique values with no keys at all. If you have ever written code to check array.includes(value) before pushing to avoid duplicates, a Set does that for you automatically. See the Set data structures article for the full method list.

let ids = new Set([1, 2, 2, 3]);
ids.size; // 3, the duplicate 2 was ignored
Ordered Keyed by Unique values Iterable
Array yes index (number) no yes
Object mostly* string/Symbol no not directly
Map yes any type no yes
Set yes n/a yes yes

*modern engines preserve insertion order for Objects, with the exception of integer-like keys which are sorted first.

What to use when
  • Use an Array when you have a list of things and order matters – a list of todos, a list of comments, results from an API call.
  • Use an Object when you’re representing a single entity with a fixed, known set of named properties – a user, a config, a single API response.
  • Use a Map when your keys aren’t simple strings, when you need to add/remove keys often, or when you care about the insertion order and quick .size lookups – caching by object reference, counting occurrences, building a lookup table on the fly.
  • Use a Set when you only care about whether something exists, not how many times or in what shape – removing duplicates from an array, tracking which IDs have already been processed, membership checks.

A simple rule of thumb: if you’re reaching for an Object just to fake a Set ({ id1: true, id2: true }) or to fake a Map ({ [nonStringKey]: value }), that’s usually a sign you should reach for the real thing instead.