liveBook · Manning

Set

As explained in Secrets of the JavaScript Ninja, Second Edition

A JavaScript collection of unique values.

A set stores distinct values, so adding an item that is already present has no effect. ES6’s built-in Set replaces a fragile workaround that mimicked sets with objects. section 9.3 section 9.3.1

Use a Set to:

  • Create an empty set or initialize one from an array. section 9.3.1
  • Check membership with has, add unique items with add, and read the item count from size. section 9.3.1
  • Iterate with for...of; values are visited in insertion order. section 9.3.1

Duplicate names stay out

Initialize a set with “Kuma,” “Hattori,” “Yagyu,” and “Hattori” again: its size is three. Add “Yoshi” to increase the size; adding “Kuma” again leaves it unchanged. section 9.3.1

Listing 9.20. Creating a set
const ninjas = new Set(["Kuma", "Hattori", "Yagyu", "Hattori"]);         #A

assert(ninjas.has("Hattori"), "Hattori is in our set");                  #B
assert(ninjas.size === 3, "There are only three ninjas in our set!");    #B

assert(!ninjas.has("Yoshi"), "Yoshi is not in, yet..");                  #C
ninjas.add("Yoshi");                                                     #C
assert(ninjas.has("Yoshi"), "Yoshi is added");                           #C
assert(ninjas.size === 4, "There are four ninjas in our set!");          #C

assert(ninjas.has("Kuma"), "Kuma is already added");                     #D
ninjas.add("Kuma");                                                      #D
assert(ninjas.size === 4, "Adding Kuma again has no effect");            #D

for(let ninja of ninjas) {                                               #E
  assert(ninja !== null, ninja);                                         #E
}                                                                        #E

See the complete example of creating a set, checking membership, adding values, checking size, and iterating. section 9.3.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines object-based imitations and demonstrates Set creation, membership, insertion, size, and iteration, while only foreshadowing set operations.
Examples
Demonstrates a set of ninja names, repeated entries, membership checks, additions, size, and insertion-order iteration.
What you can do after
Apply the built-in Set constructor to retain unique values, check membership, add items, inspect size, and iterate.
How it connects
Relates sets to arrays and maps as collections, and contrasts them with object-based imitations.

Also explained in

Compare how 15 books explain set →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.