Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Map Methods

The new Map() Method

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

Example

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

Map.get()

You can retrieve the value associated with a key in a Map by using the get() method.

Example

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

Map.get()

You can obtain the value for a key in a Map using the get() method.

Example

fruits.get(“apples”);

Map.set()

You can add elements to a Map using the set() method.

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”500);

Map.size

The size property returns the count of elements in a Map.

Example

fruits.size;

Map.delete()

The delete() method removes an element from a Map.

Example

fruits.delete(“apples”);

Map.clear()

The clear() method removes all elements from a Map.

Example

fruits.clear();

Map.has()

The has() method returns true if a key is present in a Map.

Example

fruits.has(“apples”);
fruits.delete(“apples”);
fruits.has(“apples”);

Map.forEach()

The forEach() method calls a callback function for each key/value pair in a Map.

Example

// List all entries
let text = “”;
fruits.forEach (function(value, key) {
  text += key + ‘ = ‘ + value;
})