What is the JavaScript set?

A JavaScript set is a collection of unique elements that can be traversed in the same order in which they were inserted.

A set can store primitive or object values​.

Syntax

svg viewer

Code

The example below shows how to create a set in JavaScript:

var example_set = new Set(["apple","bannana","mango","kiwi"]);
console.log(example_set)

Set class methods and properties

There are various methods and properties implemented in the Set class. A few of them are described below.

  • Set.prototype.size returns the number of elements in the set.

  • Set.prototype.add(val) adds the new element val at the end of the Set object.

  • Set.prototype.delete(val) deletes the element val from the Set object.

  • Set.prototype.clear() removes all the elements from the set.

  • Set.prototype.has(val) returns true if val is present in the Set object.

  • Set.prototype.values() returns all the values from the Set in the same insertion order.

Code

The example below shows​ how various set class methods and attributes are used:

var fruits = new Set(["apple","bannana","mango","kiwi"]);
// print size of the set
console.log(fruits.size)
// add "orange" to fruits.
fruits.add("orange")
console.log(fruits.values())
// remove "kiwi" from fruits.
fruits.delete("kiwi")
console.log(fruits.values())
// check if fruits contains "apple"
console.log(fruits.has("apple"))
// clear the set
fruits.clear()
console.log(fruits.values())
Copyright ©2024 Educative, Inc. All rights reserved