Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Sets

A JavaScript Set is a collection that holds unique values, where each value can appear only once. These values can be of any type, including primitive values or objects.

How to Create a Set

You can create a JavaScript Set by:

  1. Passing an array to new Set()
  2. Creating an empty Set and using add() to include values.

The new Set() Method

Pass an array to the new Set() constructor to create a Set:

Example

// Create a Set
const letters = new Set([“a”,“b”,“c”]);

Create a Set and include values:

Example

// Create a Set
const letters = new Set();

// Add Values to the Set
letters.add(“a”);
letters.add(“b”);
letters.add(“c”);

Create a Set and include variables:

Example

// Create a Set
const letters = new Set();

// Create Variables
const a = “a”;
const b = “b”;
const c = “c”;

// Add Variables to the Set
letters.add(a);
letters.add(b);
letters.add(c);

The add() Method

Example

letters.add(“d”);
letters.add(“e”);

If you add duplicate elements, only the first instance will be retained.

Example

letters.add(“a”);
letters.add(“b”);
letters.add(“c”);
letters.add(“c”);
letters.add(“c”);
letters.add(“c”);
letters.add(“c”);
letters.add(“c”);

Listing the Elements

You can display all Set elements (values) using a for…of loop.

Example

// Create a Set
const letters = new Set([“a”,“b”,“c”]);

// List all Elements
let text = “”;
for (const x of letters) {
  text += x;
}

Sets are Objects

typeof returns “object.”

typeof letters;      // Returns object

instanceof Set returns true.

letters instanceof Set;  // Returns true

Browser Support

Set is an ES6 feature (introduced in JavaScript 2015).

All modern browsers have fully supported ES6 since June 2017.

js1

Set is not supported in Internet Explorer.