It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 81: JavaScript Sets – Introduction and Usage

In JavaScript, a Set is a built-in object that allows you to store unique values of any type, whether primitive or object references. Unlike arrays, Sets do not allow duplicate elements, which makes them useful for storing a collection of distinct items.


What is a Set?

A Set is an ordered list of values (just like an array), but each value must be unique. If you attempt to add a duplicate, it will be ignored.

const fruits = new Set();
fruits.add("apple");
fruits.add("banana");
fruits.add("apple"); // Duplicate – will be ignored

console.log(fruits); // Set(2) {'apple', 'banana'}

Creating a Set

const mySet = new Set();
const numbers = new Set([1, 2, 3, 4]);

You can also initialize a Set with an array of values.


Common Methods

.add(value)

Adds a new element to the Set.

mySet.add("JS");

.has(value)

Checks if a value exists in the Set.

console.log(mySet.has("JS")); // true

.delete(value)

Removes a specific element from the Set.

mySet.delete("JS");

.clear()

Removes all elements from the Set.

mySet.clear();

Iterating Over a Set

Use a for...of loop to iterate through a Set:

const colors = new Set(["red", "green", "blue"]);

for (const color of colors) {
  console.log(color);
}

Try Your Hand

  • Create a Set that stores five different numbers, including a duplicate.
  • Add a new number, check if a specific number exists, then delete one of the numbers.
  • Print the final contents of the Set.

Summary

  • Sets are collections of unique values.
  • Duplicate values are not allowed.
  • Use .add(), .has(), .delete(), and .clear() to manage Sets.
  • You can loop through Sets using for...of.