🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to JavaScript Notes
Topic #70

JS Sets

A JavaScript Set is a collection of unique values.

Each value can only occur once in a Set.

The values can be of any type, primitive values or objects.


How to Create a Set

You can create a JavaScript Set by:

  • Passing an array to new Set()
  • Create an empty set and use add() to add values

The new Set() Method

Pass an array to the new Set() constructor:

Example

// Create a Set

const letters = new Set(["a","b","c"]);

Create a Set and add 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 add 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 equal elements, only the first will be saved:

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 list all Set elements (values) with 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 letters;      // Returns object

Note: Learn More: JavaScript Set Methods JavaScript Set Logic JavaScript Weak Sets JavaScript Set Reference JavaScript Maps


Browser Support

Set is an ES6 feature.

ES6 is fully supported in all modern browsers since June 2017:

Want to go beyond the notes?

Join CodingNow 2.0's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

JS Sets – FAQs

Quick answers about learning JS Sets in JavaScript.

This free note from CodingNow 2.0 explains JS Sets in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on CodingNow 2.0, including JS Sets, is 100% free with no signup required.
With focused practice, most students grasp JS Sets in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now