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
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.sizereturns the number of elements in the set. -
Set.prototype.add(val)adds the new elementvalat the end of the Set object. -
Set.prototype.delete(val)deletes the elementvalfrom the Set object. -
Set.prototype.clear()removes all the elements from the set. -
Set.prototype.has(val)returns true ifvalis 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 setconsole.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 setfruits.clear()console.log(fruits.values())
Free Resources