Sitemap
Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

ES6 — Set vs Array — What and when?

6 min readJan 24, 2018

--

Press enter or click to view image in full size
Image
Set VS Array

What is Set and what is Array?

Everyone who works with JS until now is familiar with Array (don’t tell me you don’t). But what exactly is Array?

Well, in general, Array is type of structure representing block of data (numbers, objects, etc…) allocated in consecutive memory.

Example: [1,2,3,2]

How about Set?

Set, more familiar as a Math concept, is an abstract data type which contains only distinct elements/objects without the need of being allocated orderly by index.

Example: {1,2,3}

Yup, by definition, Array and Set are technically different concepts.

One of the biggest differences here, you may notice, is that elements in Array can be duplicate (unless you tell it not to be), and in Set, they just can’t (regardless what you decide).

In addition, Array is considered as “indexed collection” type of data structure, while Set is considered as “keyed collection”.

A quick reminder for those who don’t remember,

Indexed collections are collections of data which are ordered by an index value

Keyed collections are collections which use keys; these contain elements which are iterable in the order of insertion.

Easy right? Now one may wonder, if they are different, why we bother compare between them?

In programming world, taken same data set (no duplicates), we can either use Array or Set to be our chosen structure to store this data set. However, depending on the use case, choosing the correct structure contributes to deliver optimal solution — and we want to achieve that. And in order to understand which to choose, we need understand firstly who they are, how they are built and what they are capable of. Since we have done with “who they are”, let’s move on to “how to build one” in JS.

Constructing

--

--

Frontend Weekly
Frontend Weekly

Published in Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Responses (27)