Can a Map use Functions as Keys?
Last Updated :
02 Feb, 2024
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
let myMap = new Map();
function keyFunction() {
console.log( 'Function used as a key' );
}
myMap.set(keyFunction,
'Value associated with the function key' );
console.log(myMap.get(keyFunction));
|
Output
Value associated with the function key
Share your thoughts in the comments
Please Login to comment...