Using Sets in JavaScript and React:

Hamza Ali
1 min readMay 26, 2024

Definition: An unordered grouping of unique things is called a set. Elements of the set are the objects that are part of the collection.

• Examples:

  • The Punjab province’s towns form a set.
    Each town in Punjab is part of the set.
  • The pencils in your purse form a set.
    All pencils in your bag are part of the set.
  • here’s how you can create a Set in both JavaScript and TypeScript:
  • JavaScript:
  • Sure, here’s how you can create a Set
  • JavaScript:
// Creating a set of towns in Punjab
const punjabTowns = new Set();
// Adding elements to the set
punjabTowns.add("Lahore");
punjabTowns.add("Rawalpindi");
punjabTowns.add("Faisalabad");
punjabTowns.add("Multan");
// Displaying the set
console.log("Towns in Punjab:", punjabTowns);
// Checking if a town is in the setconsole.log("Is Lahore in the set?", punjabTowns.has("Lahore"));
console.log("Is Islamabad in the set?", punjabTowns.has("Islamabad"));
// Iterating through the set
console.log("Towns in Punjab:");
punjabTowns.forEach(town => {
console.log(town);
});

Here’s how you can use a Set in a React component:

import React, { useState } from 'react';
function PunjabTowns() {

const [towns, setTowns] = useState(new Set());
const addTown = (town) => {
const updatedTowns = new Set(towns);
updatedTowns.add(town);
setTowns(updatedTowns);
};
return (
<div>
<h2>Towns in Punjab</h2>
<button onClick={() => addTown("Lahore")}>Add Lahore</button>
<button onClick={() => addTown("Rawalpindi")}>Add Rawalpindi</button>
<button onClick={() => addTown("Faisalabad")}>Add Faisalabad</button>
<button onClick={() => addTown("Multan")}>Add Multan</button>
<h3>Towns List:</h3>
<ul>
{[...towns].map((town, index) => (
<li key={index}>{town}</li>
))}
</ul>
</div>
);
}
export default PunjabTowns;

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Hamza Ali
Hamza Ali

Written by Hamza Ali

Hi! I am an experienced web and mobile app developer presently earning a degree. I enjoy developing clean, user-friendly applications that bring ideas to life.

No responses yet

Write a response