JavaScript Set add() Method

The add method of the JavaScript Set is utilized to append a new object to the conclusion of a WeakSet object.

Syntax

The syntax for the add method is illustrated as follows:

Example

weakSetObj.add(value)

Parameter

value - It represents the object to be added.

Return

The WeakSet object.

JavaScript Set add method example

In this section, we will explore the add method by examining a series of examples.

Example 1

Let’s explore an example demonstrating how to incorporate an object into a WeakSet instance.

Example

<script>

var ws = new WeakSet();

var obj1={};

var obj2={};

ws.add(obj1);

ws.add(obj2);

//Let's check whether the WeakSet object contains the added object

document.writeln(ws.has(obj1)+"<br>");

document.writeln(ws.has(obj2));

</script>

Output:

Output

true

true

Example 2

In this illustration, we will examine if we can incorporate objects into a WeakSet object without prior initialization.

Example

<script>

var ws = new WeakSet();

try

  {

ws.add(obj);

document.writeln(ws.has(obj));    

  }

catch(error)

  {

    document.writeln(error);

  }

</script>

Output:

Output

ReferenceError: obj is not defined

Input Required

This code uses input(). Please provide values below: