How to useFunction constructor in Javascript
You can create a new function object using the Function constructor, passing in the function name as a string, and then call that new function object.
Syntax:
function myFunction() {
...
}
const functionName = "myFunction";
const fn = new Function(`return ${functionName}()`);
fn();
Example: In this example, we define three variables: functionName with the value “greet”, which is the name of the function, functionArguments with the value “name”, which is the name of the function’s argument, and functionBody with the value “console.log(‘Hello, ‘ + name + ‘!’);” which is the body of the function. We then use the Function constructor to create a new function dynamically with the given arguments and body and store it in a variable dynamicFunction.
Javascript
const functionName = "greet" ; const functionArguments = "name" ; const functionBody = `console.log( 'Hello, ' + name + '!' );`; // Using the Function constructor // to create and execute the function const dynamicFunction = new Function(functionArguments, functionBody); dynamicFunction( "John" ); |
Hello, John!
How to execute a function when its name as a string in JavaScript ?
To execute a function when its name is a string in JavaScript, we have multiple approaches. In this article, we are going to learn how to execute a function when its name is a string in JavaScript.
Example:
function myFunction() {
...
}
const functionName ="myFunction";
Below are the approaches used to execute a function when its name is a string in JavaScript:
Table of Content
- Using eval() Method
- Using window[]
- Using Function constructor