Discover the versatility of Set and Map data structures in JavaScript and how they can enhance your coding experience.
Set is a new data structure introduced in ES6 that allows you to store unique values of any type, whether primitive values or object references. Let's explore how Set can be used in JavaScript:
const uniqueNumbers = new Set();
uniqueNumbers.add(1);
uniqueNumbers.add(2);
uniqueNumbers.add(3);
console.log(uniqueNumbers); // Set { 1, 2, 3 }
console.log(uniqueNumbers.has(2)); // true
console.log(uniqueNumbers.has(4)); // false
Map is another ES6 data structure that allows you to store key-value pairs. Let's dive into how Map can be leveraged in JavaScript:
const userRoles = new Map();
userRoles.set('John', 'Admin');
userRoles.set('Alice', 'Editor');
userRoles.set('Bob', 'Viewer');
console.log(userRoles); // Map { 'John' => 'Admin', 'Alice' => 'Editor', 'Bob' => 'Viewer' }
for (const [user, role] of userRoles) {
console.log(`${user} is a ${role}`);
}
Set and Map offer efficient ways to handle data in JavaScript, providing unique features that can streamline your coding process. Experiment with these data structures to enhance your programming skills!