Categories
JavaScript Answers

How to call a JavaScript function named in a variable?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *