Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js Sets in JavaScript

Js Sets in JavaScript

? JavaScript Set

A Set is a built-in object that lets you store unique values of any type, whether primitive or objects.


What is a Set?

  • Stores unique values (no duplicates).

  • Can store any type: numbers, strings, objects, etc.

  • Useful when you want to keep track of distinct items.


Creating a Set

const mySet = new Set();const numbers = new Set([1, 2, 3, 4, 4]); console.log(numbers); // Set(4) {1, 2, 3, 4} — duplicates ignored

Basic Operations

OperationExampleResult
Add valuemySet.add(5);Adds 5 to the set
Check existencemySet.has(3);Returns true if 3 exists
Delete valuemySet.delete(2);Removes 2 if present
Get sizemySet.size;Number of elements
Clear allmySet.clear();Removes all elements

Example Usage

const fruits = new Set();fruits.add("apple");fruits.add("banana");fruits.add("apple");  // ignored, duplicateconsole.log(fruits.has("banana"));  // trueconsole.log(fruits.size);            // 2fruits.delete("banana");console.log(fruits.has("banana"));  // false

Iterating Over a Set

const colors = new Set(["red", "green", "blue"]);for (const color of colors) {  console.log(color);}

Why Use Sets?

  • To remove duplicates from arrays easily:

const numbers = [1, 2, 2, 3, 4, 4];const uniqueNumbers = [...new Set(numbers)];console.log(uniqueNumbers); // [1, 2, 3, 4]

If you want, I can explain WeakSet or Set methods in more detail!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql