JavaScript Sets

A Set is a collection of unique values, without duplicates. Sets provide methods to add, delete, and check the presence of elements efficiently.

Key Topics

Creating Sets

Use the new Set() constructor to create a set. Duplicates are automatically removed.

let mySet = new Set(["A", "B", "A"]);
console.log(mySet);

Output

> Set { "A", "B" }

Explanation: The duplicate "A" is removed, resulting in a set with "A" and "B" only.

Common Set Operations

Methods like add(), has(), and delete() manage set elements.

mySet.add("C");
console.log(mySet.has("B"));
mySet.delete("A");
console.log(mySet);

Output

> true

> Set { "B", "C" }

Explanation: "C" is added, "B" is confirmed present, "A" is removed, leaving "B" and "C".

Iterating Sets

Use for...of to loop through set values.

JavaScript Usage in DOM

Sets can track unique user inputs or selections, displayed on the webpage without duplicates.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sets in DOM</title>
</head>
<body>
    <h1>Set Demo</h1>
    <button onclick="showSet()">Show Set</button>
    <p id="output"></p>

    <script>
        function showSet() {
            let uniqueItems = new Set(["Item1", "Item2", "Item1"]);
            let result = "";
            for (let val of uniqueItems) {
                result += val + " ";
            }
            document.getElementById("output").textContent = result;
        }
    </script>
</body>
</html>

Key Takeaways

  • Unique Values: Sets store unique elements.
  • Methods: add(), has(), delete() manage elements.
  • Iteration: for...of loops easily over set values.
  • DOM Integration: Represent unique collections without duplicates on webpages.