Start learning free

LESSON 230 OF 671 · SETS

Sets in JavaScript

Lesson Read the full explanation

TL ; DR:

A Set holds values without repeats. Adding a value that is already in it changes nothing.


let pets = new Set(["cat", "dog", "cat"]);   // cat goes in once

pets.add("fish");                            // a new value

pets.add("dog");                             // already in it, no change

console.log(pets.size);                      // 3

console.log(pets.has("dog"));                // true


Full lesson:

An array keeps every value you put in it, repeats too. Sometimes you only need to know which values there are. A set is made for that.

A set holds each value once. Adding a value that is already in it changes nothing.

  • new Set() makes an empty set.
  • s.add(x) puts x in the set s.
  • s.has(x) is true when x is in the set.
  • s.size gives how many values the set holds.
  • new Set(arr) builds a set from the array arr. Its repeats go in once.

Checking s.has(x) is fast, even for a big set. An array's includes looks at the values one by one.

Watch the names. A set counts with size, not length. It checks with has, not includes.

A JavaScript set keeps the order you added values in. Still, it has no indexes. s[0] is undefined.


Your task

The camp's sign-up array, names, has some names twice. Build a set named kids from it.

Then Zoe signs up, and Ava signs up again. Add both names to kids.

Last, if kids has "Leo", print Leo is coming.

The code already prints the number of kids twice.

Expected output:

3 kids
4 kids
Leo is coming
STEP 1 OF 3
    Ctrl + Enter to check

    JAVASCRIPT · SETS

    Sets in JavaScript, explained

    What a set is

    An array keeps every value you put in it, repeats included. Sometimes you only need to know which values there are. A Set is made for that: it holds each value once, and adding a value that is already in it changes nothing.

    let pets = new Set(["cat", "dog", "cat"]);   // cat goes in once
    pets.add("fish");                            // a new value
    pets.add("dog");                             // already in it, no change
    console.log(pets.size);                      // 3
    console.log(pets.has("dog"));                // true
    

    The four things to know

    • new Set() makes an empty set.
    • s.add(x) puts x in the set s.
    • s.has(x) is true when x is in the set.
    • s.size says how many values the set holds.

    new Set(arr) builds a set from an array, and the repeats go in once. A string works too, because it is iterable: new Set("hello").size is 4, since the two l letters count once.

    Checking s.has(x) is fast, even for a big set. An array's includes looks at the values one by one, so on a long array it takes longer.

    From an array to a set and back

    A common use of a set is to remove repeats from an array. Build a set from the array, then spread the set into a new array with [...]. The values keep the order in which they were first added:

    let names = ["Ava", "Leo", "Ava", "Mia", "Leo"];
    let unique = [...new Set(names)];
    console.log(unique);
    console.log(unique.length);
    
    [ 'Ava', 'Leo', 'Mia' ]
    3
    

    Notice that the new array has a length, because it is an array again. You can also start from an empty set and fill it one value at a time with add. Calls to add can be chained, since each one returns the set: after seen.add("Ava").add("Leo"), the size is 2.

    Traps

    • The names differ from arrays. A set counts with size, not length, and checks with has, not includes. For the set pets above, pets.length and pets.includes are both undefined.
    • No indexes. A JavaScript set remembers the order you added values in, but it has no positions: pets[0] is undefined. To get an array back, spread it: [...pets].
    • Values are compared exactly. The number 1 and the string "1" are different values, so new Set([1, "1"]).size is 2.
    • Two sets are never === just because they hold the same values. The comparison is about the object itself, not its contents.
    • add returns the set. You can ignore the result, which is what the exercise does.

    The exercise, step by step

    The camp's sign-up array names has some names twice. The task is to build a set kids from it, add "Zoe" and then "Ava", and print Leo is coming if kids has "Leo". The starter code already prints the number of kids twice.

    1. Build the set below names: let kids = new Set(names);. Ava and Leo are in the array twice, but each goes in the set once, so kids holds 3 names.
    2. Below the first console.log, call add with "Zoe" and then with "Ava". Only Zoe makes the set bigger; Ava is already in it.
    3. At the end, check kids.has("Leo") and print the message.
    let names = ["Ava", "Leo", "Ava", "Mia", "Leo"];
    let kids = new Set(names);
    console.log(kids.size + " kids");
    kids.add("Zoe");
    kids.add("Ava");
    console.log(kids.size + " kids");
    if (kids.has("Leo")) {
        console.log("Leo is coming");
    }
    

    The output is:

    3 kids
    4 kids
    Leo is coming
    

    Key takeaways

    • A set holds each value once; add on a value it already has does nothing.
    • Use size, add and has, not length, push and includes.
    • new Set(array) removes repeats in one step.
    • A set has no indexes, so s[0] is undefined.
    Keep going with JavaScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free