Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Maps

A Map stores key-value pairs where the keys can be of any data type.

It also preserves the original insertion order of the keys.

How to Create a Map

You can create a JavaScript Map by either passing an array to new Map() or by using Map.set() to add key-value pairs.

The new Map() Method

A Map can be created by passing an array to the new Map() constructor.

Example

// Create a Map
const fruits = new Map([
  [“apples”500],
  [“bananas”300],
  [“oranges”200]
]);

The set() Method

You can create a Map by providing an array to the new Map() constructor.

Example

// Create a Map
const fruits = new Map();

// Set Map Values
fruits.set(“apples”500);
fruits.set(“bananas”300);
fruits.set(“oranges”200);

The set() method can also be used to update existing values in a Map.

Example

fruits.set(“apples”200);

The get() Method

The get() method retrieves the value associated with a key in a Map.

Example

fruits.get(“apples”);    // Returns 500