call function by variable javascript

How to Call Function Using Variable Name in JavaScript

Typically, when we call functions in JavaScript we mention its entire name as a literal. Sometimes, the name of your function may be present in a variable, and you may need to call it using the variable. In this case, we will learn how to call function using variable name in JavaScript.


How to Call Function Using Variable Name in JavaScript

Here are the steps to call function using variable name in JavaScript.

Let us say you have defined a function in JavaScript as shown below.

function hello_world(){
  alert('hello world');
}

Typically, we call the above function as shown below.

<script>
   hello_world();
</script>

Let us say your function name is stored in another variable as shown below.

var a="hello_world";

Now you cannot call the above defined function as shown below since it will look for function a() instead of hello_world().

<script>
  a();
</script>

So the right way to call a function using a string is

window["functionName"](arguments);

For example, here is how to call the above hello_world() function.

window["hello_world"]();
OR
window[a]();

The window namespace holds references to all functions.

If you have defined your JavaScript function in a Namespace, you need to modify the function call as shown.

window["Namespace"]["functionName"](arguments);

In this article, we have learnt how to call function using variable name in JavaScript. It is useful if you want call functions using variables, instead of literal strings. It also allows you to dynamically change which function to be called based on variable value.

Also read:

How to Detect Tab/Browser Closing in JavaScript
How to Include Another HTML in HTML File
How to Call Function When Page is Loaded in JavaScript
How to Match Exact String in JavaScript
How to Convert Columns to Rows in Pandas

Leave a Reply

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