.get()

Published Dec 31, 2021Updated May 15, 2024
Contribute to Docs

Retrieves a value associated with a given key in a Map object.

Syntax

The .get() method accepts a key parameter and checks it against a Map object. If the key exists in the map, the associated value is returned. If not, undefined is returned.

map.get(key);

Example

Values are retrieved by their keys from Map objects using the .get() method.

const fruits = new Map([
['Apples', 5],
['Oranges', 8],
]);
console.log(fruits.get('Apples')); // Output: 5
console.log(fruits.get('Oranges')); // Output: 8
console.log(fruits.get('Bananas')); // Output: undefined

Codebyte Example

The code below uses a new Map that contains purchase orders. In this example:

  • Samantha will get the next purchase order that she needs to fill from the map using the .get() method.
  • Once the purchase order has been worked, Samantha will remove it from the map using the .delete() method.
Code
Output
Loading...

All contributors

Looking to contribute?

Learn JavaScript on Codecademy