Sometimes, we want to call a JavaScript function named in a variable.
In this article, we’ll look at how to call a JavaScript function named in a variable.
How to call a JavaScript function named in a variable?
To call a JavaScript function named in a variable, we can get the function by the string key.
For instance, we write
function foo() {
alert("foo");
}
const a = "foo";
window[a]();
to get the foo
global function with window[a]
, which evaluates to window.foo
.
And then we call that.
Conclusion
To call a JavaScript function named in a variable, we can get the function by the string key.