Just Learn Code

Mastering the JavaScript Set Object: Creating Adding Removing Looping and Using WeakSets

JavaScript has been a widely used programming language for web development since its creation. One of its significant features is the JavaScript Set object, which is a collection of unique values.

It has various methods that allow developers to perform different operations on the set. In this article, we will examine the syntax for creating an empty set, the use of iterable objects, and different methods available on the Set object.

Syntax for creating a new empty Set

Creating an empty Set is a simple process that can be done in just one line of code. The syntax for creating an empty Set is as follows:

“`

const mySet = new Set();

“`

In the above code, the `mySet` variable stores the newly created Set object.

The `Set()` constructor is used to create a new Set. The new Set object created is completely empty, with no values inside.

Optional iterable object and its use

An iterable object is any object that can be looped over using a for..of loop. Sets are iterable objects, which means that you can add a collection of values to the Set object using an iterable object.

For example, let’s create an array containing some unique names and use it to create a Set object. “`

const namesArr = [‘John’, ‘Alex’, ‘Emma’, ‘John’, ‘Liam’];

const namesSet = new Set(namesArr);

“`

In the above code, the `namesArr` variable holds the array containing unique names.

The `namesSet` variable stores the newly created Set object, which is created from the `namesArr` using the `Set()` constructor. The duplicated names in the array will be removed when the Set object is created since the Set object can only contain unique values.

Useful Set methods

Sets have many useful methods that allow developers to perform different operations on the set. Some of the most commonly used methods include `add()`, `clear()`, `delete()`, `entries()`, `forEach()`, `has()`, `keys()`, and `@@iterator`.

add() method and its use

The `add()` method is used to add a new value to the Set object. The syntax for using this method is as follows:

“`

mySet.add(value);

“`

In the code above, the `value` parameter is the value you want to add to the `mySet` Set object.

The method returns the modified Set object, which allows developers to chain the methods together.

clear() method and its use

The `clear()` method deletes all values from the Set object, leaving it completely empty. This is a useful method when you want to clear the entire Set instead of deleting individual items.

The syntax for using this method is as follows:

“`

mySet.clear();

“`

delete() method and its use

The `delete()` method removes a specific value from the Set object. The syntax for using this method is as follows:

“`

mySet.delete(value);

“`

In the above code, `value` is the value you want to delete from the Set object.

If the value is not in the Set object, no action is taken. The method returns a boolean value indicating whether the value was deleted or not.

entries() method and its use

The `entries()` method returns an iterator over the Set object. The iterator returns an array containing both the value and the key of each element in the Set object.

The syntax for using this method is as follows:

“`

for (let entry of mySet.entries()) {

console.log(entry);

}

“`

In the above code, `entry` is an array containing both the value and the key of each element in the Set object. The `entries()` method is useful for looping through the Set object and getting both the value and the key.

forEach() method and its use

The `forEach()` method applies a callback function to each element in the Set object. The syntax for using this method is as follows:

“`

mySet.forEach((value, valueAgain, set) => {

console.log(value);

});

“`

In the above code, the callback function is executed for each element in the Set object.

The `value` parameter is the value of the current element, and `set` is the Set object itself. The `valueAgain` parameter is the same as the `value` parameter and is included for compatibility with other forEach methods.

has() method and its use

The `has()` method returns a boolean indicating whether a particular value exists in the Set object. The syntax for using this method is as follows:

“`

mySet.has(value);

“`

In the above code, `value` is the value you want to check for in the Set object.

The method returns a boolean value `true` if the value is present and `false` if it is not.

keys() method and its use

The `keys()` method returns an iterator over the Set object. The iterator returns the values in the Set object in the order of insertion.

The syntax for using this method is as follows:

“`

for (let key of mySet.keys()) {

console.log(key);

}

“`

In the above code, `key` is the value at the current position in the `mySet` Set object. The `keys()` method is useful for looping through the Set object and getting only the values.

@@iterator method and its use

The `@@iterator` method returns an iterator over the Set object. The iterator returns the values in the Set object in the order of insertion.

The syntax for using this method is as follows:

“`

for (let item of mySet[Symbol.iterator]()) {

console.log(item);

}

“`

In the above code, `item` is the value at the current position in the `mySet` Set object. The `@@iterator` method is useful for looping through the Set object and getting only the values.

Conclusion

The JavaScript Set object is a useful feature for web development tasks that involve handling collections of unique values. This article covered the syntax for creating an empty Set and how to use iterable objects.

We also examined some useful methods of Set objects, including `add()`, `clear()`, `delete()`, `entries()`, `forEach()`, `has()`, `keys()`, and `@@iterator`. By understanding these methods, developers can work more efficiently with Set objects and create better web applications.

JavaScript Set examples

In this article, we will explore various examples of the JavaScript Set object. We will cover how to create a new Set from an array, how to check the size of a Set, how to add elements to a Set, how to check if a value is present in a Set, how to remove elements from a Set, and how to loop through the elements of a Set using different methods.

We will also examine one of the advanced features of JavaScript, the

WeakSets.

Creating new Set from an Array

One of the ways to create a new Set object is by using an array. The code below demonstrates how to create a new Set object from an array:

“`

const fruitsArr = [‘Apple’, ‘Banana’, ‘Cherry’, ‘Apple’, ‘Banana’];

const fruitsSet = new Set(fruitsArr);

console.log(fruitsSet);

“`

In the above code, we created an array of fruits containing both unique and duplicate values.

We then passed the `fruitsArr` array as an argument to the `Set()` constructor to create a new Set. The output of the code will be a Set object with only unique values because Sets cannot contain duplicate values.

Checking size of a Set

To check the number of elements in a Set object, we use the `size` property. The `size` property returns the number of elements in the Set object.

The code below demonstrates how to check the size of a Set object:

“`

const fruitsArr = [‘Apple’, ‘Banana’, ‘Cherry’];

const fruitsSet = new Set(fruitsArr);

console.log(fruitsSet.size);

“`

In the above code, we created a new Set object from an array of fruits. We then logged the value of the `size` property to the console.

The output of the code will be 3, which is the number of elements in the `fruitsSet` Set object.

Adding elements to a Set and chaining the add() method

To add a new element to a Set object, we use the `add()` method. The `add()` method takes a single parameter, which is the value to be added to the Set object.

The code below demonstrates how to add a new element to a Set object:

“`

const fruitsSet = new Set([‘Apple’, ‘Banana’]);

fruitsSet.add(‘Cherry’).add(‘Durian’);

console.log(fruitsSet);

“`

In the above code, we created a new Set object from an array of fruits. We then chained the `add()` method multiple times to add new elements to the `fruitsSet` Set object.

The output of the code will be a Set object with four elements (Apple, Banana, Cherry, and Durian).

Checking if a value is in a Set using the has() method

To check if a value is present in a Set, we use the `has()` method. The `has()` method returns a boolean value indicating whether the specified value is present in the Set object.

The code below demonstrates how to use the `has()` method to check if a value is in a Set object:

“`

const fruitsSet = new Set([‘Apple’, ‘Banana’, ‘Cherry’]);

console.log(fruitsSet.has(‘Banana’)); // true

console.log(fruitsSet.has(‘Durian’)); // false

“`

In the above code, we created a new Set object from an array of fruits. We then used the `has()` method to check if ‘Banana’ and ‘Durian’ are present in the `fruitsSet` Set object.

The output of the code will be `true` for the first `console.log` statement and `false` for the second `console.log` statement.

Removing elements from a Set using the delete() method

To remove an element from a Set, we use the `delete()` method. The `delete()` method takes a single parameter, which is the value to be removed from the Set object.

The code below demonstrates how to remove an element from a Set object:

“`

const fruitsSet = new Set([‘Apple’, ‘Banana’, ‘Cherry’]);

fruitsSet.delete(‘Cherry’);

console.log(fruitsSet);

“`

In the above code, we created a new Set object from an array of fruits. We then used the `delete()` method to remove the ‘Cherry’ element from the `fruitsSet` Set object.

The output of the code will be a Set object with two elements (Apple and Banana). Looping the elements of a Set using for…of loop

To loop through the elements of a Set, we use the `for…of` loop.

The `for…of` loop is an ES6 feature that allows us to loop through elements of an iterable object. The code below demonstrates how to use the `for…of` loop to loop through the elements of a Set object:

“`

const fruitsSet = new Set([‘Apple’, ‘Banana’, ‘Cherry’]);

for (let fruit of fruitsSet) {

console.log(fruit);

}

“`

In the above code, we created a new Set object from an array of fruits.

We then used the `for…of` loop to loop through the elements of the `fruitsSet` Set object. The output of the code will be all the elements of the `fruitsSet` Set object.

Invoking a callback function on each element of a Set using forEach() method

The `forEach()` method allows us to invoke a callback function on each element of a Set. The callback function takes up to three arguments: the first argument is the value of the current element, the second argument is the same as the first argument, and the third argument is the Set object itself.

The code below demonstrates how to use the `forEach()` method to invoke a callback function on each element of a Set object:

“`

const fruitsSet = new Set([‘Apple’, ‘Banana’, ‘Cherry’]);

fruitsSet.forEach((value, valueAgain, set) => {

console.log(value);

});

“`

In the above code, we created a new Set object from an array of fruits. We then used the `forEach()` method to invoke a callback function on each element of the `fruitsSet` Set object.

The output of the code will be all the elements of the `fruitsSet` Set object.

WeakSets

A WeakSet is a data structure that allows us to store weak references to objects. A weak reference in JavaScript is a reference that does not prevent the garbage collector from collecting an object.

The `WeakSet()` constructor is used to create a new WeakSet object. The code below demonstrates how to create a new WeakSet object:

“`

const fruitsWeakSet = new WeakSet([{name: ‘Apple’}, {name: ‘Banana’}, {name: ‘Cherry’}]);

“`

In the above code, we created a new WeakSet object containing three objects with a `name` property.

Since the objects contained in the WeakSet are weakly referenced, they are eligible for garbage collection when there are no other references to them outside of the WeakSet. Comparison of

WeakSets with Sets and WeakMaps

One difference between

WeakSets, Sets, and WeakMaps is that

WeakSets can only contain objects as elements, while Sets can contain any value as elements.

WeakMaps, on the other hand, can only contain objects as keys. Another difference is that

WeakSets do not have a `size` property and cannot be iterated over like Sets and WeakMaps.

Use of

WeakSets to check for a specified value

WeakSets are useful when we want to check if an object is present in a set without keeping a reference to the object. The code below demonstrates how to use

WeakSets to check for a specified value:

“`

const fruit1 = {name: ‘Apple’};

const fruit2 = {name: ‘Banana’};

const fruit3 = {name: ‘Cherry’};

const fruitsWeakSet = new WeakSet([fruit1, fruit2, fruit3]);

console.log(fruitsWeakSet.has(fruit2)); // true

fruit2 = null; // removing the reference

console.log(fruitsWeakSet.has(fruit2)); // false

“`

In the above code, we created three objects with a `name` property.

We then added them as elements of a WeakSet object using the `WeakSet()` constructor. The `has()` method is used to check if `fruit2` is present in the `fruitsWeakSet` WeakSet object.

We then set `fruit2` to `null` to remove the reference to the object and re-checked if it was present in the `fruitsWeakSet` WeakSet object using the `has()` method. Since the reference to the object has been removed, the output of the second `console.log` statement will be `false`.

Conclusion

In conclusion, we explored various examples of the JavaScript Set object, including creating a new Set from an array, checking the size of a Set, adding elements to a Set, checking if a value is present in a Set, removing elements from a Set, and looping through the elements of a Set using different methods. We also examined

WeakSets and their use cases, as well as the differences between

WeakSets, Sets, and WeakMaps.

These examples will be useful for developers who want to work efficiently with collections of unique values in JavaScript. This article covered important aspects of the JavaScript Set object, including creating, adding elements, removing elements, checking for the presence of elements, looping through elements, and using

WeakSets.

We saw how to leverage these powerful features to enhance our web app development. By mastering these techniques, web developers can streamline their operations and create more efficient code that offers a better user experience.

The JavaScript Set object encourages better code organization and is a must-learn for every developer who wants to excel at web development.

Popular Posts