Perdamaian
Perdamaian

Reputation: 43

What does "Sets are to arrays as maps are to objects" mean?

I'm learning about ES6 and stumbled upon this phrase in this video that states: 'you could say that Sets are to Arrays as Maps are to Objects'.

What does this phrase mean ? Why is a Set more linked to arrays than maps are ? (and vice-versa for objects).

I know this is a really specific question, but my head is really turning since i've heard this phrase!

Thank you in advance, i'm new to question on SO so any comment is appreciated.

Upvotes: 4

Views: 32

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371019

A Set is a collection of values, just like an array is a collection of values (no keys involved, except .length / .size)

A Map is a collection of key-value pairs, just like an object is a collection of key-value pairs. (though the keys of a Map can be anything, not just strings)

Of course, there are many more differences, but the distinction between values and key-value pairs is what's most relevant for what you're asking.

Map and object example:

const key = 'key';
const value = 'value';

const map = new Map();
const obj = {};

map.set(key, value);
obj[key] = value;

Set and array example:

const value = 'value';

const set = new Set();
const arr = [];

set.add(value);
arr.push(value);

Upvotes: 3

Related Questions