Home > Back-end >  How to execute a function from the value of a map object [closed]
How to execute a function from the value of a map object [closed]

Time:09-16

I want to be able to execute a function which is saved as a value on Map object by referencing the key. For example:

const myMap = new Map();

myMap.set("myKey", function(argument) {
    console.log(argument);
});

let value = myMap.get("myKey");
console.log(value);

The function is output to the console but I can't figure out how to actually execute the function.

I tried let test = new Function(value) but got the error message "Function statements require a function name"

CodePudding user response:

Invoke the function with parentheses:

const myMap = new Map();

myMap.set("myKey", function(argument) {
    console.log(argument);
});

let value = myMap.get("myKey");
value('Hello World!')

CodePudding user response:

As get method of myMap will give you the function, You just have to invoke it as

myMap.get("myKey")("Hello World!")

const myMap = new Map();

myMap.set("myKey", function (argument) {
  console.log(argument);
});

let value = myMap.get("myKey")("Hello World!");

  • Related