Introduction to Maps in JavaScript – All You Have to Know




Have you ever ever heard about maps in JavaScript? Maps are a brand new object kind that was launched in ES2015. On this tutorial, you’ll be taught all you should find out about this lesser recognized object kind. You’ll find out about what maps in JavaScript are, how they work and learn how to use them.

Fast introduction to maps

As a JavaScript developer you in all probability know JavaScript objects. Objects help you retailer knowledge within the type of a key-value pair. Maps are similar to JavaScript objects. While you wish to retailer some knowledge in maps, you retailer these knowledge additionally within the type of a key-value pair.

Additionally similar to with objects, you’ll be able to add new keys and delete current, and retrieve their values from maps. While you evaluate maps and objects, there are some variations you need to find out about. Let’s check out these variations earlier than shifting additional.

Maps vs Objects

One of the vital variations is that, in relation to maps in JavaScript, you should utilize any knowledge kind to create keys. You need to use even objects or features. Objects will help you use solely strings or a symbols. One other vital distinction is the order of keys-value pairs.

In maps, keys are ordered primarily based on the order you’ve added them to the map. If you happen to iterate over a map, you’re going to get its keys in the identical order by which you’ve created them. In case of objects, that is true since ES2015 and just for JavaScript engines that help this specification. Earlier than ES2015, keys in objects weren’t ordered.

One other distinction is how straightforward it’s to get the scale of a map. Like set, each map has a measurement property that claims what number of key-value pairs it accommodates. With objects, you would need to use keys() or values() to get an array of keys or values. Then, use size to get the size of this array to lastly get the scale of an object.

One other good factor is that maps, like array, are iterable. You don’t need to get the keys or values first with the intention to iterate over them. You are able to do it immediately. For instance, you should utilize forEach() method, similar to with array. You may also use for…of loop, similar to with objects.

The final distinction, that’s good to know, is that maps are optimized for including and eradicating of key-value pairs. Objects aren’t. This may increasingly not matter if you happen to don’t want to control with knowledge typically. If you happen to do utilizing maps could make it easier to enhance efficiency of your JavaScript code.

Creating maps in JavaScript

Maps are just like objects. One factor that’s totally different between them, among the many issues we simply mentioned, is the way you create them. While you wish to create a brand new object, there are a number of choices to do this. For instance, you should utilize new Object(), Object.create(), object literal or object constructor.

While you wish to create a brand new map, there are two methods to do it. Nicely, theoretically. The primary choice to create new maps is by creating new empty Map object utilizing new Map() and assigning it values later.

// Creating new map
let myMap = new Map()

From array to map

The second possibility can be about utilizing new Map() to create new Map object. Nevertheless, you may also go in an array. To make this work, this array must be structured in a selected method. It has to include nested array for every key-value pair. Every array (key-value pair) has to include two gadgets, the important thing and the worth.

// Create new map and assign it some values immediately
const myMap = new Map([
  ['name',  'Jackie'],
  ['gender', 'female'],
  ['age', 23]
])

// Log the content material of "myMap" map
console.log(myMap)
// Output:
// Map { 'identify' => 'Jackie', 'gender' => 'feminine', 'age' => 23 }

From object to map

You need to use the second possibility additionally with objects. You’ll be able to take current object and get all its entries with entries() methodology. The entries() methodology returns all entries in the identical format because the array you noticed within the earlier instance. So, you’ll be able to go the results of calling entries() methodology to the Map() object.

// Create new object
const myObj = {
  topic: 'Math',
  degree: '1',
  issue: 'Medium'
}

// Create new map from "myObj"
const myMap = new Map(Object.entries(myObj))

// Log the content material of "myMap" map
console.log(myMap)
// Outputs:
// Map { 'topic' => 'Math', 'degree' => '1', 'issue' => 'Medium' }


// Or, a bit longer
// Create new object
const myObj = {
  topic: 'Math',
  degree: '1',
  issue: 'Medium'
}

// Get all entries
const myObjEntries = Object.entries(myObj)

// Create new map from "myObjEntries"
const myMap = new Map(myObjEntries)

// Log the content material of "myMap" map
console.log(myMap)
// Outputs:
// Map { 'topic' => 'Math', 'degree' => '1', 'issue' => 'Medium' }

Including values to maps

While you wish to add values, key-value pairs, to an object there are two ways to do this. Nicely, three, if you happen to depend including values throughout object initialization. The primary is utilizing do notation. The second is utilizing sq. brackets. The second method, sq. brackets, works additionally with maps.

That mentioned, including values to maps utilizing sq. brackets just isn’t a great follow. The issue is that while you do that you’ll lose efficiency optimizations maps have. The appropriate method so as to add values to maps is through the use of set() methodology. This methodology accepts two parameters. First is for the key and second for the worth.

// Create new map
const myMap = new Map()

// Create easy operate
operate sayHi() {
  return 'Hiya!'
}

// Add some values (key-value pairs) to "myMap"
myMap.set('identify', 'James Reacher')
myMap.set('bio', { age: 35, peak: 189, weight: 82 })
myMap.set(sayHi, 'Perform as a key?')

// Log the content material of "myMap"
console.log(myMap)
// Output:
// Map {
//   'identify' => 'James Reacher',
//   'bio' => { age: 35, peak: 189, weight: 82 },
//   [Function: sayHi] => 'Perform as a key?'
// }

While you wish to add a number of key-value pairs to a map you are able to do it just one on the time. One fascinating factor is that maps help chaining. So, sure, it’s important to use set() methodology for each key-value pair you wish to add. Nevertheless, you’ll be able to chain these strategies so that you don’t have to make use of the identify of the map again and again.

// Create new map
const myMap = new Map()

// Add some values utilizing chaining
myMap.set('Language', 'JavaScript')
  .set('Writer', 'Brendan Eich')
  .set('First appeared', '1995')

// Log the content material of "myMap"
console.log(myMap)
// Output:
// Map {
//   'Language' => 'JavaScript',
//   'Writer' => 'Brendan Eich',
//   'First appeared' => '1995'
// }

Eradicating values from maps

While you wish to take away values from maps the method is straightforward. There’s a methodology it’s important to use referred to as delete(). This methodology accepts one parameter, the important thing of the key-value pair you wish to take away. If the deletion is profitable, the delete() methodology will return true. If the important thing doesn’t exist, it’ll return false.

One factor to recollect about delete() methodology is that it really works solely with one key on the time. You’ll be able to’t go in a number of keys. If you happen to strive it the delete() methodology will take away solely the primary key. It can ignore the remaining.

// Create new map
const myMap = new Map()

// Add some values to "myMap"
myMap.set('identify', 'Joe')
myMap.set('age', 25)

// Log the content material of "myMap"
console.log(myMap)
// Output:
// Map { 'identify' => 'Joe', 'age' => 25 }

// Take away "identify" from "myMap"
myMap.delete('identify')

// Log the content material of "myMap" once more
console.log(myMap)
// Output:
// Map { 'age' => 25 }


// This won't work
// Create new map
const myMap = new Map()

// Add some values to "myMap"
myMap.set('identify', 'Joe')
myMap.set('age', 25)

// Attempt to take away "identify" and "age" on the similar time
myMap.delete('identify', 'age')

// Log the content material of "myMap" once more
// Trace: solely the "identify" can be eliminated
// as a result of it was the primary parameter
console.log(myMap)
// Output:
// Map { 'age' => 25 }

Eradicating all values from maps

Eradicating values with delete() methodology is useful while you wish to take away only one or few values. If you wish to take away all values in a map directly, there’s a higher and sooner strategy to do it. Other than overwriting the map, you are able to do this additionally with clear() methodology. This methodology doesn’t settle for any parameters.

// Create new map
const myMap = new Map()

// Add some values to "myMap"
myMap.set('The Lean Startup', 'Eric Ries')
myMap.set('Measure What Issues', 'John Doerr')
myMap.set('The Startup Proprietor's Handbook', 'Steve Clean')

// Log the content material of "myMap"
console.log(myMap)
// Output:
// Map {
//   'The Lean Startup' => 'Eric Ries',
//   'Measure What Issues' => 'John Doerr',
//   "The Startup Proprietor's Handbook" => 'Steve Clean'
// }

// Take away all values from "myMap"
myMap.clear()

// Log the content material of "myMap"
console.log(myMap)
// Output:
// Map {}

Retrieving values from maps

Including and eradicating values from maps is easy. You’ll be able to say the identical about retrieving them. While you wish to retrieve a selected worth from a map you should utilize get() methodology. This methodology accepts one parameter, a key that’s related to the worth you wish to retrieve.

If the important thing its worth you wish to retrieve exists, it’ll return the worth. If it doesn’t exist it’ll return undefined.

// Create new map
const myMap = new Map()

// Add some values to "myMap"
myMap.set('front-end', 'React')
myMap.set('back-end', 'Node.js')
myMap.set('database', 'MongoDB')

// Get the worth of "back-end" key
myMap.get('back-end')
// Output:
// 'Node.js'

// Attempt to get the worth of non-existent key "cms"
myMap.get('cms')
// Output:
// undefined

Checking if worth exists in map

In some sense, the get() methodology may make it easier to examine if some key exists in a map. Nevertheless, there’s a methodology devoted for this. This methodology is known as has(). Equally to get(), the has() methodology additionally accepts one parameter, the key you might be in search of. If the important thing exists has() returns true. If not, it returns false.

// Create new map
const myMap = new Map()

// Add some values to "myMap"
myMap.set('language', 'English')

// Test if "myMap" has "language" key
myMap.get('language')
// Output:
// true

// Test if "myMap" has "compiler" key
myMap.get('compiler')
// Output:
// false

Getting the scale of the map

Within the “Maps vs Objects” we mentioned that one of many advantages of maps is that it’s straightforward to seek out out their measurement. That is true. Each Map object has its personal measurement property. This property is analogous to the length property that exists on arrays. Utilizing this measurement property will shortly inform you what number of key-value pairs are there in a selected map.

// Create new map
const myMap = new Map()

// Log the scale of "myMap"
console.log(myMap.measurement)
// Output:
// 0

// Add some values to "myMap"
myMap.set('Tony Stark', 'Iron Man')
  .set('Steve Rogers', 'Captain America')
  .set('Black Widow', 'Natasha Romanoff')
  .set('Bruce Banner', 'Hulk')

// Log the scale of "myMap" once more
console.log(myMap.measurement)
// Output:
// 4

Iterating over maps

You understand how so as to add values to maps and learn how to take away them. You additionally know learn how to retrieve values, one after the other. Query is, what if you wish to retrieve all values from a map? There are 4 choices you’ll be able to select from. These choices are keys(), values(), entries() and forEach() strategies.

Map.keys(), Map.values() and Map.entries()

The primary three strategies all return Iterator object hat include particular knowledge. The primary methodology, keys(), returns an Iterator with keys, one key for every pair within the Map. The second methodology, values() Iterator with values, additionally one worth for every pair within the Map. The third methodology entries() returns an iterable for all entries.

These entries are returned within the type of a [key, value]. While you use these three strategies you’ll be able to then iterate over the returned Iterator object with subsequent() methodology and its worth property. Each use of subsequent() methodology, together with worth, will return the subsequent worth within the iterator, subsequent worth, key or entry within the map.

// Create new map
const myMap = new Map()

// Add some values
myMap.set('First identify', 'Joshua Doer')
myMap.set('E mail', '[email protected]')
myMap.set('username', 'josh1234')


// Instance no.1: Map.keys()
// Create iterator for keys
const myKeysIterator = myMap.keys()

// Log the primary key
console.log(myKeysIterator.subsequent().worth)
// Output:
// 'First identify'

// Log the second key
console.log(myKeysIterator.subsequent().worth)
// Output:
// 'E mail'

// Log the third key
console.log(myKeysIterator.subsequent().worth)
// Output:
// 'username'


// Instance no.2: Map.values()
// Create iterator for values
const myValuesIterator = myMap.values()

// Log the primary worth
console.log(myValuesIterator.subsequent().worth)
// Output:
// 'Joshua Doer'

// Log the second worth
console.log(myValuesIterator.subsequent().worth)
// Output:
// '[email protected]'

// Log the third worth
console.log(myValuesIterator.subsequent().worth)
// Output:
// 'josh1234'


// Instance no.3: Map.entries()
// Create iterator for entries
const myEntriesIterator = myMap.entries()

// Log the primary entry
console.log(myEntriesIterator.subsequent().worth)
// Output:
// [ 'First name', 'Joshua Doer' ]

// Log the second entry
console.log(myEntriesIterator.subsequent().worth)
// Output:
// [ 'Email', '[email protected]' ]

// Log the third entry
console.log(myEntriesIterator.subsequent().worth)
// Output:
// [ 'username', 'josh1234' ]

Maps, iterators and for…of loop

Utilizing the subsequent() and worth won’t be the most effective instrument if you wish to get all knowledge from Iterator object directly. For this, a greater possibility can be for...of loop. This loop lets you iterate over an Iterator and get all knowledge inside, with out the necessity to use subsequent() a number of instances.

// Create new map
const myMap = new Map()

// Add some values
myMap.set('First identify', 'Joshua Doer')
myMap.set('E mail', '[email protected]')
myMap.set('username', 'josh1234')


// Create iterator for entries
// NOTE: this may work in the identical method
// additionally for keys() and values()
const myEntriesIterator = myMap.entries()

// Loop over the iterate object "myEntriesIterator"
for (let iteratorItem of myEntriesIterator) {
  // Log every merchandise within the iterator
  console.log(iteratorItem)
}
// Output:
// [ 'First name', 'Joshua Doer' ]
// [ 'Email', '[email protected]' ]
// [ 'username', 'josh1234' ]

Map.forEach()

The forEach() methodology is a bit totally different. It doesn’t return Iterator object like keys(), values() and entries() and allows you to iterate over these values manually. As an alternative, forEach() iterates over the map straight It additionally robotically iterates over all key-value pairs.

When it iterates over the pairs it executes a callback operate for every of them. This callback operate accepts three parameters. All these parameters are non-obligatory. These parameters are worth, key and map. The worth lets you entry present worth in every iteration.

The key lets you entry present key within the iteration. The final one, the map, lets you entry the entire map you might be iterating over.

// Create new map
const myMap = new Map()

// Add some values
myMap.set('title', 'JavaScript: The Definitive Information')
myMap.set('writer', 'David Flanagan')
myMap.set('writer', 'O'Reilly Media')

// Loop over "myMap" map straight
myMap.forEach((worth, key) => {
  // Log key and worth within the map
  console.log(`${key}: ${worth}`)
})
// Output:
// 'title: JavaScript: The Definitive Information'
// 'writer: David Flanagan'
// "writer: O'Reilly Media"

From maps to things

that you could create maps from objects. You may also do the alternative. You’ll be able to take current map and use it to create new object. This may be finished with fromEntries() methodology. At first, you used entries() methodology to create an array from entries that exist inside an object.

The fromEntries() methodology does the alternative factor. It takes an array, within the type of [key, value], and transforms it into an object. The entries() methodology that exists on map will make it easier to remodel any map into an array you want. You’ll be able to then use that array with fromEntries() methodology to create new object.

// Create new map
const myMap = new Map()

// Add some values
myMap.set('spanish', 'Buenos dias')
myMap.set('french', 'Bonjour')
myMap.set('russian', 'Доброе утро')

// Rework the map into an array
const myTransformedMap = myMap.entries()

// Create new object from reworked map
const myObj = Object.fromEntries(myTransformedMap)

// Log the content material of "myObj"
console.log(myObj)
// Output:
// {
//   spanish: 'Buenos dias',
//   french: 'Bonjour',
//   russian: 'Доброе утро'
// }

Conclusion: Introduction to maps in JavaScript

Maps are one of many lesser recognized, and fewer regularly used, object sorts in JavaScript. I hope this tutorial helped you be taught what maps in JavaScript are, how they work and learn how to use them. I additionally hope it helped you distinguish when they could be a more sensible choice than objects.

If you happen to preferred this text, please subscribe so you do not miss any future publish.








If you would like to help me and this weblog, you’ll be able to turn into a patron, or you should buy me a espresso 🙂







Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#Introduction #Maps #JavaScript