Cookie Consent by Free Privacy Policy Generator 📌 Set and Map in JavaScript: A Close Look

🏠 Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeiträge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden Überblick über die wichtigsten Aspekte der IT-Sicherheit in einer sich ständig verändernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch übersetzen, erst Englisch auswählen dann wieder Deutsch!

Google Android Playstore Download Button für Team IT Security



📚 Set and Map in JavaScript: A Close Look


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

In the world of JavaScript, there are several ways to handle and organize data, with arrays and objects being the most popular. However, ES6 (the sixth edition of the ECMAScript standard) introduced two useful data structures: Set and Map. These structures offer unique advantages that can be indispensable in specific scenarios.

 

📌 Table of Contents

  • What is a Set?
    • Creating a Set
    • Adding Values to a Set
    • Checking the Size of a Set
    • Checking if a Value Exists in a Set
    • Removing Values
    • Iterating Over a Set
  • What is a Map?
    • Creating a Map
    • Setting Key-Value Pairs
    • Getting Values
    • Checking the Size of a Map
    • Checking if a key Exists in a Map
    • Removing Key-Value Pairs
    • Iterating Over a Map
  • Set vs. Array: When to Use Which?
  • Map vs. Object: When to Use Which?
  • Wrapping Up

 

What is a Set?

 

A Set in JavaScript is a collection of values where each value must be unique. This means no duplicate values are allowed. The values can be of any type, and the order of values in the set does not matter.

 

Creating a Set

 

Creating a set is simple. Use the new keyword followed by Set().

let mySet = new Set()

// console.log(mySet) 
// Output: Set(0) {}

 

Adding Values to a Set

 

We can add values to a set using the add method:

mySet.add(1)
mySet.add(5)
mySet.add('JavaScript')

// console.log(mySet) 
// Output: Set(3) { 1, 5, 'JavaScript' }

 

Checking the Size of a Set

 

To check how many elements are in a Set, use the size property:

console.log(mySet.size) // Output: 3

 

Checking if a Value Exists in a Set

 

To check if a value is in a Set, use the has method:

console.log(mySet.has(1)) // Output: true
console.log(mySet.has(2)) // Output: false

 

Removing Values

 

Remove a specific element with the delete method:

mySet.delete(5)

Or clear the entire Set with the clear method:

mySet.clear()

 

Iterating Over a Set

 

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

for (let item of mySet) {
  console.log(item)
}

Or using forEach method:

mySet.forEach((value) => {
  console.log(value)
})

 

What is a Map?

 

A Map is a collection of key-value pairs, similar to an object, but with a few key differences. In a Map, keys can be of any data type, not just strings or Symbols. Also, maps maintain the order of insertion, which isn't guaranteed in plain objects.

 

Creating a Map

 

To create a Map, we can use the new keyword, optionally passing an array of key-value pairs:

let myMap = new Map()

// console.log(myMap) 
// Output: Map(0) {}

 

Setting Key-Value Pairs

 

Use the set method to add key-value pairs to the Map:

myMap.set('name', 'JavaScript')
myMap.set(1, 'ES6')
myMap.set(true, 'boolean')

// console.log(myMap) 
// Output: Map(3) { 'name' => 'JavaScript', 1 => 'ES6', true => 'boolean' }

 

Getting Values

 

Retrieve a value by key using the get method:

console.log(myMap.get('name')) // Output: 'JavaScript'

 

Checking the Size of a Map

 

Similar to Set, Map have a size property:

console.log(myMap.size) // Output: 3

 

Checking if a key Exists in a Map

 

Check for the existence of a key using has:

console.log(myMap.has('name')) // Output: true

 

Removing Key-Value Pairs

 

Remove a specific key-value pair with the delete method:

myMap.delete('name')

Or clear the entire Map with the clear method:

myMap.clear()

 

Iterating Over a Map

 

Iterate through a Map's keys, values, or entries with the keys, values, and entries methods, respectively:

for (let key of myMap.keys()) {
  console.log(key)
}

for (let value of myMap.values()) {
  console.log(value)
}

for (let [key, value] of myMap.entries()) {
  console.log(key, value)
}

We can also use the forEach method:

myMap.forEach((value, key) => {
  console.log(key, value);
})

 

Set vs. Array: When to Use Which?

 

Understanding when to use a Set instead of an Array can be crucial for both the performance and clarity of our code. While both can store collections of values, they serve different purposes.

 

Uniqueness

If our primary concern is to prevent duplicate values, a Set automatically ensures that all elements are unique. With an Array, we would have to manually check for duplicates before adding a new element.

 

Performance

When it comes to performance, especially for large collections of data, Set is more performant for checking the existence of an element within it. This is because Set is implemented with efficient data structures under the hood that allow for faster lookup.

 

Map vs. Object: When to Use Which?

 

While Map and Object in JavaScript can appear to serve similar functions as collections of key-value pairs, there are significant differences that could affect which one we should use.

 

Key Flexibility

Map accepts keys of any data type, whereas an Object only accepts Strings and Symbols as keys.

 

Iteration Order

Map maintains the order of elements as they were inserted, while the order of keys in a plain object is not guaranteed.

 

Size Determination

 

A Map directly provides the size property, making it easy to determine the number of key-value pairs. With an Object, we would typically use Object.keys(obj).length, which is less direct.

 

Performance

For frequent additions and removals of key-value pairs, Map is more performant than using an Object.

 

Wrapping Up

 

Both Set and Map are robust constructs in JavaScript that can greatly enhance the way we work with collections of data. With the knowledge of how to utilize these structures, we'll be able to write cleaner, more efficient code.

 

rich-text-editor-for-react npm package

Demo | Documentation

...



📌 Set and Map in JavaScript: A Close Look


📈 46.69 Punkte

📌 Set and Map in JavaScript: A Close Look


📈 46.69 Punkte

📌 <self-close /> or <not-to-self-close></not-to-self-close>


📈 36.19 Punkte

📌 Apple TV+ shares first look at ‘The New Look,’ starring Glenn Close; coming February 14, 2024


📈 28.37 Punkte

📌 How to Use Set and Map in JavaScript


📈 26.47 Punkte

📌 How to Use the JavaScript Map and Set Objects – Explained with Code Examples


📈 26.47 Punkte

📌 Google Contemplating Removing Chrome 'Close Other Tabs' and 'Close Tabs to the Right' Options


📈 25.81 Punkte

📌 Chrome May Soon Lose "Close Other Tabs" and "Close Tabs to the Right" Options


📈 25.81 Punkte

📌 Refactorización de código JavaScript para Startups: Eficiencia con Set y Map


📈 24.78 Punkte

📌 Oracle Hyperion Financial Close Management 11.1.2.4 Close Manager unknown vulnerability


📈 24.13 Punkte

📌 Close to the Sun Xbox One review: It doesn't fly close enough


📈 24.13 Punkte

📌 Oracle Hyperion Financial Close Management 11.1.2.4 Close Manager unknown vulnerability


📈 24.13 Punkte

📌 AppStories, Episode 305 – A Close-Up Look at Anybox and Spring


📈 21.91 Punkte

📌 A close look at Fallout Exploit Kit and Raccoon Stealer


📈 21.91 Punkte

📌 wp-google-map-plugin Plugin up to 2.3.9 on WordPress Map cross site request forgery


📈 20.49 Punkte

📌 Medium CVE-2021-30457: Id-map project Id-map


📈 20.49 Punkte

📌 Medium CVE-2021-30456: Id-map project Id-map


📈 20.49 Punkte

📌 Medium CVE-2021-30455: Id-map project Id-map


📈 20.49 Punkte

📌 CVE-2023-47223 | WP Map Plugins Basic Interactive World Map Plugin up to 2.0 on WordPress cross site scripting


📈 20.49 Punkte

📌 Zomato: Zomato Map server going out of memory while resizing map image


📈 20.49 Punkte

📌 Valorant Icebox Map: Players Are Dodging The New Map In Ranked


📈 20.49 Punkte

📌 DOT To Map Out Nation's Time Zones After Report Shows No Official Map Exists


📈 20.49 Punkte

📌 Sort a Map in Go by Value (Sort Map by Value)


📈 20.49 Punkte

📌 CVE-2024-22297 | Codeboxr CBX Map for Google Map & OpenStreetMap Plugin up to 1.1.11 on WordPress cross site scripting


📈 20.49 Punkte

📌 The World Map with Many Faces — Map Projections


📈 20.49 Punkte

📌 Juno Probe To Get First Up-Close Look At Jupiter On Saturday


📈 20.22 Punkte

📌 Take a Close Look at Faraday Future’s (Supposed) Tesla-Killer


📈 20.22 Punkte

📌 Juno Probe To Get First Up-Close Look At Jupiter On Saturday


📈 20.22 Punkte

📌 Take a Close Look at Faraday Future’s (Supposed) Tesla-Killer


📈 20.22 Punkte

📌 Extensive iPhone X Hands-On Video Provides Close-up Look at Anniversary Model


📈 20.22 Punkte

📌 An Up-Close Look At the Parker Solar Probe -- the Spacecraft That Will Skim the Sun's Surface


📈 20.22 Punkte











matomo