Open In App

Can a Map use Functions as Keys?

In JavaScript, a Map can have functions as keys. Unlike objects, which internally convert keys to strings (or, in the case of symbols, to unique symbols), Map objects allow keys of any data type, including functions, to be used without any automatic conversion.

Example: Here, a function keyFunction is used as a key in the Map, and a corresponding value is associated with it using the set() method. Later, the get() method is used to retrieve the value associated with the function key.




// Creating a Map with a function as a key
let myMap = new Map();
 
function keyFunction() {
  console.log('Function used as a key');
}
 
myMap.set(keyFunction,
'Value associated with the function key');
 
// Retrieving the value using the function key
console.log(myMap.get(keyFunction));

Output
Value associated with the function key
Article Tags :