To execute a JavaScript function when you have its name as a string, you can use the eval()
function. The eval() function is a global function in JavaScript that evaluates a string as
JavaScript code.
You execute a JavaScript function using :
- eval()
- window object
- call() or apply()
eval()
Here is an example of how to use the eval() function to execute a function:
Keep in mind that the eval() function is generally considered to be a dangerous and
insecure function to use, as it can execute any JavaScript code that is passed to it. It is usually
better to avoid using eval() whenever possible and to find an alternative solution.
function greet() {
return 'Hello, world!';
}
const functionName = 'greet';
eval(functionName + '()'); // Output: 'Hello, world!'
window object
If you have the name of the function stored in a variable and you want to call the function, you can
also use the window object to access the function by its name. Here is an example:
Here is an example of how to use the window object to execute a function:
function greet() {
return 'Hello, world!';
}
const functionName = 'greet';
window[functionName] = greet;
window[functionName](); // Output: 'Hello, world!'
call() or apply()
Alternatively, you can also use the call() or apply() methods of the function
to execute it. Here is an example:
Note that the call() and apply() methods allow you to pass arguments to the
function when you execute it.
Here is an example of how to use the call() and apply() function to execute a function:
function greet() {
return 'Hello, world!';
}
const functionName = 'greet';
window[functionName] = greet;
window[functionName].call(); // Output: 'Hello, world!'
window[functionName].apply(); // Output: 'Hello, world!'