JavaScript Sets

JavaScript Sets

JavaScript Sets

 

In JavaScript, a Set is a built-in object that allows you to store unique values of any type, whether primitive values or object references. The values are stored in insertion order, which means that they can be iterated over in the order they were added.

Here’s an example of creating a new Set:

				
					let mySet = new Set(); 
				
			

You can add values to a Set using the “add()” method, like this:

				
					mySet.add("hello");
mySet.add(42);
mySet.add(true);

				
			

In this example, we’re adding a string, a number, and a boolean value to the Set.

You can check the size of a Set using the “size” property:

This code will output “3” to the console.

				
					console.log(mySet.size);
				
			

You can check if a Set contains a specific value using the “has()” method:

				
					console.log(mySet.has(42));
				
			

This code will output “true” to the console, since the Set contains the value 42.

You can remove values from a Set using the “delete()” method:

				
					mySet.delete(true);
				
			

In this example, we’re removing the boolean value from the Set.

You can iterate over the values in a Set using the “for…of” loop:

				
					for (let value of mySet) {
  console.log(value);
}

				
			

This code will output the values “hello” and 42 to the console, in that order.

Sets can be useful when you need to store a collection of values without duplicates. They also have other methods like “clear()” to remove all values and “forEach()” to perform a function on each value in the set.

Join To Get Our Newsletter
Spread the love