2
43

JavaScript: How to add data to JavaScript Set

Reading Time: < 1 minute

There are 2 methods to add unique data or values to JavaScript Set standard built-in object. Either during initialisation phase or runtime phase after the set is initialised. Let’s look into how it is done.

Phase to add data

  • Initialisation
  • Runtime

Before we go into the details, we have a more in-dept post here on how to create and use JavaScript Set for basic understanding.

Add data to Set on Initialisation

Below show the illustration on initialise set with data. It is simply having an array to hold onto a list of values. We can initialise a Set with values of different datatype at the same time.

After initialisation, we will be able to get the results.

const mySet = new Set(['Person1', 101]);

console.log(mySet.has('Person1'));  // true
console.log(mySet.has(101));        // true
console.log(mySet.has('101'));      // false

Add data to Set during Runtime

If there is a need to insert new value in the middle of the code, we can utilise add() method to tell Set to include new values into its dataset one at a time. In top of that, values can also be of different datatype.

const nameSet = new Set();

nameSet.add('Person1');
nameSet.add(101);

console.log(nameSet.has('Person1'));  // true
console.log(nameSet.has('Person2'));  // false
console.log(mySet.has(101));          // true
console.log(mySet.has('101'));        // false

Conclusion

To add data to any JavaScript Set, we can either perform it during the initialisation phase or use add() method to insert new values.

For other examples, can refer to MDN documentation here.

Show Comments

No Responses Yet

Leave a Reply