How to call function from it name stored in a string using JavaScript ?
In this article, we will call a function from the string stored in a variable. There are two methods to call a function from a string stored in a variable.
Note: The eval() method is older and is deprecated
[Approach 1]: Using the window object
The window object in HTML 5 references the current window and all items contained in it. Hence we can use it to run a function in a string along with parameters to the function.
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to call function from string stored
in a variable using JavaScript
</b>
<p>
Click on the button to call the
function in the string
</p>
<p class="example">
GeeksforGeeks is a computer
science portal.
</p>
<button onclick="evaluateFunction()">
Click here
</button>
<script type="text/javascript">
function changeColor(color) {
document.querySelector('.example').style
= `color: ${color}`;
}
function evaluateFunction() {
stringFunction = "changeColor";
param = 'green';
window[stringFunction](param);
}
</script>
Syntax:
window[functionName](parameters)[Approach 2]: Using the eval() method
- The other method that can be used is the eval() method.
- The string that may be passed on to the function may include a JavaScript expression, statement, or a sequence of statements.
- It can also have variables and properties of existing objects.
- The only problem with this method is that it is considered unsafe and may not be supported by newer browsers.
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to call function from string stored
in a variable using JavaScript
</b>
<p>
Click on the button to call the
function in the string
</p>
<p class="example">
GeeksforGeeks is a computer
science portal.
</p>
<button onclick="evaluateFunction()">
Click here
</button>
<script type="text/javascript">
function changeColor(color) {
document.querySelector('.example').style
= `color: ${color}`;
}
function evaluateFunction() {
stringFunction = "changeColor('green')";
eval(stringFunction);
}
</script>