To initialize a set in JavaScript, you can use the Set
object.
In this example,
Set
constructor, which is a built-in constructor in JavaScript, to create a new, empty set.set1
and assign it the result of calling the new Set()
constructor.new Set()
constructor creates an empty set.set1
to the console to verify its contents. An empty set in JavaScript is represented as Set {}
.const set1 = new Set();
console.log('Contents of set1:', set1);
Contents of set1: Set {}
In this example,
Set
constructor to create a new set and initialize it with elements.set2
and assign it the result of calling the new Set()
constructor.set2
using the add
method. For example, we add the strings 'apple'
, 'banana'
, and 'cherry'
.set2
to the console to verify its contents.const set2 = new Set();
set2.add('apple');
set2.add('banana');
set2.add('cherry');
console.log('Contents of set2:', set2);
Contents of set2: Set { 'apple', 'banana', 'cherry' }
In this tutorial, we learned How to Initialize a Set in JavaScript language with well detailed examples.