Skip to content

JavaScript set() method

  • by

JavaScript set() method is a set method, which is used to add a new element to the set. The Set object is a built-in data structure that represents an unordered collection of unique values. The syntax of the set() method is as follows:


JavaScript set() method example

A simple example code first creates a new Set object called mySet and add three values to it.

<!DOCTYPE html>
  <script >
    let mySet = new Set();


    // duplicate value




JavaScript set() method

If the value already exists in the set, the set() method does nothing and returns the original Set object.

JavaScript set() methods

add()Adds a new element to the set. If the element already exists in the set, the add() method does nothing.
clear()Removes all elements from the set.
delete()Removes the specified element from the set. Returns a boolean indicating whether the element was successfully removed or not.
entries()It returns an object of Set iterator that contains an array of [value, value] for each element.
forEach()It executes the specified function once for each value.
has()Returns a boolean indicating whether the specified element exists in the set.
values()Returns a new iterator object that contains the values in the set.

Do comment if you have any doubts or suggestions on this JS method topic

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *