Learnitweb

Set in JavaScript

1. Introduction

Set is a collection of unique values. Value in the Set can be primitive value or object reference. Values in Set can be iterated in the insertion order.
Each value in the Set is unique so a value will not be found twice in the Set.

2. Value equality

  • The values in the Set are compared for equality using the === operator.
  • -0 and +0 are considered equal.
  • NaN is considered equal to NaN in case of Set, even though NaN != NaN.

3. Create a new Set

You can create a new Set using Set() constructor.

const set = new Set();

4. Append a value to Set

The add(value) method can be used to append a value to the Set object. The method returns the Set object with added value.

const set = new Set();

set.add("hello");
set.add("one");
console.log(set); //Set(2) { 'hello', 'one' }

5. Delete a value

The delete(value) removes the element. This method returns true if the element was successfully removed otherwise returns false.

const set = new Set();

set.add("hello");
set.add("one");
console.log(set); //Set(2) { 'hello', 'one' }

//delete a value
set.delete("hello");
console.log(set); // Set(1) { 'one' }

6. Remove all elements

The clear() method removes all elements from the Set.

const set = new Set();

set.add("hello");
set.add("one");
console.log(set); //Set(2) { 'hello', 'one' }

//remove all the elements
set.clear();
console.log(set); // Set(0) {}

7. Check if the value exists in Set

The has(value) returns true if the element is present in the Set else returns false.

const set = new Set();

set.add("hello");
set.add("one");
console.log(set); //Set(2) { 'hello', 'one' }

console.log(set.has("one")); // true

8. Number of values in Set

The size property returns the number of values in the Set.

const set = new Set();

set.add("hello");
set.add("one");
console.log(set); //Set(2) { 'hello', 'one' }

console.log(set.size); // 2

9. Iterating Set values

The values() returns a new iterator object that yields the values for each element in the Set. The values are returned in the insertion order.

const set = new Set();

set.add("one");
set.add("two");
set.add("three");
set.add("four");
set.add("five");

for (let item of set.keys()) {
  console.log(item);
}

//one
//two
//three
//four
//five