Sets and Maps

 Sets and Maps


Sets and maps are built-in data structures in JavaScript that provide efficient ways to store unique values and key-value pairs, respectively.


// Set

const set = new Set();

set.add(1);

set.add(2);

set.add(3);

set.add(2); // Ignored, already exists


console.log(set.size); // Output: 3

console.log(set.has(2)); // Output: true


// Map

const map = new Map();

map.set('name', 'John');

map.set('age', 30);


console.log(map.size); // Output: 2

console.log(map.get('name')); // Output: John

console.log(map.has('age')); // Output: true

In the example above, a set is created using the Set constructor, and values are added using the add method. Sets automatically eliminate duplicate values. A map is created using the Map constructor, and key-value pairs are added using the set method. Maps provide efficient retrieval of values based on keys using the get method.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...