Basic JavaScript Syntax

Maps

What are Maps?

A JavaScript Map is an object that holds key:value pairs (where the keys can be any datatype ) and remembers the original insertion order of the keys . You can create a map two ways:

  1. by passing an array to new Map()
  2. by creating a map and using Map.set()

JavaScript Code for creating maps.
Image source: N.Dobbin (for HyperionDev Course IFS L4T15: JavaScript Refresher, 2022)

JavaScript Map methods

JavaScript has a number of built in Map instance methods (you can find them all at MDN Web Docs ). Some basic map methods are listed below:

  • has() - checks to see if a key exists in the map and returns a boolean
  • get() - returns the value of the given key
  • delete() - deletes the given key-value pair from the map
  • clear() - removes all key-value pairs in a map


Method examples and output:
JavaScript map methods examples.
Image source: N.Dobbin (for HyperionDev Course IFS L4T15: JavaScript Refresher, 2022)
JavaScript map methods output examples.
Image source: N.Dobbin (for HyperionDev Course IFS L4T15: JavaScript Refresher, 2022)

You can find more tutorials and examples for each method at w3schools .





Practice what you've learned!

Question 1:

True or false: The has() method checks to see if a key exists in the map and returns a boolean.


Question 2:

Which of the following is the correct syntax for the get() method?