Javascript Maps

Maps are a new data strucure in es6 designed to store key / value pairs.

Maps are designed to replace object literals for storing key/value pairs. Using the new map data structure is beneficial because it gives us access to some handy properties. These properties allow us to iterate over maps, use any data type as keys and easily add or remove data.

Storing key/value pairs (the old way)

We can use object literals to store key/value pairs. For example:

                     var oldCar = {
                        "make": "Toyota",
                        "model": "Corolla",
                        "year":  1999
                    console.log(oldCar.year) // retrieve the value of the year of the oldCar.

Creating a map to store key/value pairs (the new way)

Create a new instance of a Map. Use the `set` keyword to set the key value pairs and the `get` keyword to retrieve values. For example:

                     // the new way
                        let newCar = new Map(); // create a new instance of Map.
                        // set the key / value pairs

                        console.log(newCar.get('year')); // retrieve the value of the year of the newCar.

The size method for Maps

Determine the number of unique keys in the Map

                     console.log(newCar.size); // checks size of the map. Expected output: 3;

                    console.log(newCar.size); // expected output still 3. We just overwrote the value for the key `year`

Delete elements from a Map

The delete property of maps lets you remove a key from the map.

                     // use the `delete` method to remove coffee in the shopping cart

Check to see if key exists in the Map

The `has` property of sets lets you check if items are in the set.

                     // use the `has` method to check if these keys exist in the newCar map.
                        console.log(newCar.has('year')); // true
                        console.log(newCar.has('brakes')); // false

  • SEO
  • Online Advertising
  • Online Ordering For Restaurants
  • Data Analytics

  • External Resources 4 Developers
  • CSS Tricks
  • MDN

  • is a Power BI and Tableau resource site around data visualizations and building business dashboards.

    Data Analytics consultants in Edmonton, Alberta specializing in Tableau and marketing analytics

    Copyright 2020 Terms / All rights reserved.