Open In App

Can a Map use Functions as Keys?

Last Updated : 02 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Javascript




// 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

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads