set js

Understanding Set JS

Set JS is a built-in JavaScript data structure that allows storing unique values of any type. It is similar to an array, but unlike an array, it only stores unique values. This means that if you try to add a value to a Set that already exists in the Set, it will not add it again. Set values can be of any data type, including primitive data types (such as numbers, strings, and booleans) and object references.

Creating a Set

To create a Set in JavaScript, you can use the Set constructor:

const mySet = new Set();

This will create an empty Set. You can also initialize a Set with an array:

const mySet = new Set([1, 2, 3]);

This will create a Set with the values 1, 2 and 3.

Adding and Removing Values

To add a value to a Set, you can use the add() method:

mySet.add(4);

This will add the value 4 to the Set. To remove a value from a Set, you can use the delete() method:

mySet.delete(4);

This will remove the value 4 from the Set.

Checking if a Value exists in a Set

You can check if a value exists in a Set using the has() method:

mySet.has(3); // returns true

This will return true if the value 3 exists in the Set and false otherwise.

Iterating over a Set

You can iterate over a Set using the for...of loop:

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

This will log each value in the Set to the console.

Multiple Ways to Create a Set

There are multiple ways to create a Set in JavaScript. You can also create a Set using an array and the spread operator:

const myArray = [1, 2, 3];
const mySet = new Set([...myArray]);

This will create a Set with the values 1, 2 and 3.

Another way to create a Set is by using a Set literal:

const mySet = new Set([1, 2, 3]);

This will create a Set with the values 1, 2 and 3.

Syntax Highlighting

To add syntax highlighting to your code, you can use highlight.js. First, include the highlight.js library in your HTML file:

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.2.0/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.2.0/highlight.min.js"></script>

Then, wrap your code block in <pre><code> tags and add the language class to the <code> tag:

<pre><code class="javascript">const mySet = new Set([1, 2, 3]);</code></pre>

This will add syntax highlighting to your code block.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe