JavaScript Set add() Method - JavaScript Tutorial

JavaScript Set add() Method

BLUF: This tutorial on JavaScript Set add() Method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript Set add() Method

Understanding JavaScript Set add() Method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience