Maps: The Key Values Collection

Maps: The Key Values Collection
Table of Contents
  1. Creating a Map
  2. Set
  3. Get
  4. Size
  5. Has
  6. Delete
  7. Clear

Maps in JavaScript are an object type that allow you to store collections in key-value pairs. You can think of how a dictionary works in the sense that if you want to know the definition of a word (the value), you only need to locate the word itself (the key).

Use maps when you want to store key-value pairs.
Use maps when you want to store key-value pairs.

Creating a Map

Creating a map in JavaScript is the same as creating any object; using the new keyword.

	
    var map = new Map();
	

With your map defined, you can move on to adding elements to it.

Set

Adding an element to a map is actually done by setting an element. The idea here is that you're "setting" an entry to your map.

	
    var map = new Map();

    map.set("red", "apple");
    map.set("blue", "blueberry");
    map.set("green", "pear");

    console.log(map);
	
	
    0: {"red" => "apple"}
    1: {"blue" => "blueberry"}
    2: {"green" => "pear"}
	

Get

After you have populated a map with some elements, you can get them back by using the get method and pass in the key.

	
    var map = new Map();

    map.set("red", "apple");
    map.set("blue", "blueberry");
    map.set("green", "pear");

    var item = map.get("blue");
    console.log(item);
	
	
    blueberry
	

Great, we got back the value for the given key!

Size

Getting the size of a map is as simple as just using the size property.

	
    var map = new Map();

    map.set("red", "apple");
    map.set("blue", "blueberry");
    map.set("green", "pear");

    console.log(map.size);
	
	
    3
	

Has

Instead of getting an element then checking if it is null or even exists, you can use the has method to check if a map has a key and it returns true if it exists and false if not.

	
    var map = new Map();

    map.set("red", "apple");
    map.set("blue", "blueberry");
    map.set("green", "pear");

    console.log(map.has("red"));
    console.log(map.has("yellow"));
	
	
    true
    false
	

Delete

To get rid of an element in a map after it has been set, call the delete method on it.

	
    var map = new Map();

    map.set("red", "apple");
    map.set("blue", "blueberry");
    map.set("green", "pear");

    map.delete("blue");

    console.log(map);
	
	
    0: {"red" => "apple"}
    1: {"green" => "pear"}
	

With blue deleted, only red and green exist.

Clear

Clearing a map will delete all elements inside it, resetting it to a state as if it were a brand new map.

	
    var map = new Map();

    map.set("red", "apple");
    map.set("blue", "blueberry");
    map.set("green", "pear");

    map.clear();

    console.log(map);
	
	
    {}