JavaScript Map keys()

Definition and usage

keys() The method returns an iterator object containing all keys of the Map.

keys() The method does not change the original Map.

Instance

Example 1

// Create a Map
const fruits = new Map([
  ["apples", 500],
  ["bananas", 300],
  ["oranges", 200]
]);
// List all keys
let text = "";
for (const x of fruits.keys()) {
  text += x;
}

Try it yourself

Object as key

Note:The ability to use objects as keys is an important feature of Map.

Example 2

// Create objects
const apples = {name: 'Apples'};
const bananas = {name: 'Bananas'};
const oranges = {name: 'Oranges'};
// Create a Map
const fruits = new Map();
// Add new elements to Map
fruits.set(apples, 500);
fruits.set(bananas, 300);
fruits.set(oranges, 200);

Try it yourself

Remember:The key is an object (apples), not a string ("apples"):

Example 3

fruits.get("apples");  // Returns undefined

Try it yourself

Syntax

map.keys()

Parameters

None.

Return value

Type Description
Iterator An iterable object containing all keys of Map.

Browser support

map.keys() Is a feature of ECMAScript6 (ES6).

From June 2017, all modern browsers support ES6 (JavaScript 2015):

Chrome Edge Firefox Safari Opera
Chrome 51 Edge 15 Firefox 54 Safari 10 Opera 38
May 2016 April 2017 Junali 2017 Junali 2016 Junali 2016

map.keys() Haiwahatiji katika Internet Explorer.