Maps Fundamentals In JavaScript

Maps Fundamentals In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Maps Fundamentals In JavaScript.

Maps Fundamentals In JavaScript

In JavaScript, a Map is a collection of key-value pairs. The keys can be any value (including primitive types and object references), and the values can also be any value. Maps are similar to objects, but they have several advantages over objects for certain use cases.

Here’s an example of how to create a Map in JavaScript:

Code To Create Map In JavaScript

let map = new Map();

You can also create a Map with an initial set of key-value pairs, like this:

let map = new Map([
  ["name", "John"],
  ["age", 30],
  ["city", "New York"]
]);

You can add new key-value pairs to a Map using the set() method, like this:

set() Method

map.set("address", "123 Main St");

You can get the value associated with a key in a Map using the get() method, like this:

get() Method

console.log(map.get("name"));

Output

“John”

You can check if a key is in a Map using the has() method, like this:

had() Method

if (map.has("name")) {
  console.log("The map contains the key 'name'.");
}

You can remove a key-value pair from a Map using the delete() method, like this:

delete() Method

map.delete("name");

You can loop through the key-value pairs in a Map using a for...of loop, like this:

for (let [key, value] of map) {
  console.log(key + ": " + value);
}

You can also use the size property to get the number of key-value pairs in a Map, like this:

size Property

console.log(map.size);

Maps also have other useful methods like clear() to clear all the key-value pairs, keys() to return an iterator object for the keys, values() to return an iterator object for the values, and entries() to return an iterator object for the [key, value] pairs.

Conclusion

Maps are useful when you need to store a collection of key-value pairs and you don’t need to maintain any particular order. Maps are also useful when you need to perform operations such as adding, updating, and removing key-value pairs.

Also, objects can use only string as key but maps can use any type of value as key, this is a major difference between the two.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment