How to turn a String into a JavaScript function call?

In JavaScript, you can dynamically call a function by converting a string containing the function name into an actual function call. This is useful when function names are determined at runtime.

Using window Object (Browser)

The most common method in browsers is using the window object to access globally defined functions:

<html>
<body>
    <script>
        function myFunction(argument) {
            alert('My function ' + argument);
        }
        
        let functionName = 'myFunction';
        window[functionName]('is working.');
    </script>
</body>
</html>

Using eval() Method

Another approach is using eval(), though it's not recommended for security reasons:

<html>
<body>
    <script>
        function greet(name) {
            console.log('Hello, ' + name + '!');
        }
        
        let functionCall = 'greet("Alice")';
        eval(functionCall);
    </script>
</body>
</html>

Using Function Constructor

You can also create and execute functions from strings using the Function constructor:

<html>
<body>
    <script>
        let functionBody = 'console.log("Dynamic function executed!");';
        let dynamicFunction = new Function(functionBody);
        dynamicFunction();
    </script>
</body>
</html>

Comparison

Method Security Performance Recommended
window[functionName]() Safe Fast Yes
eval() Risky Slow No
Function constructor Moderate Moderate Sometimes

Best Practices

When calling functions dynamically, always validate the function name to prevent security issues. Use typeof to check if the function exists before calling it:

<html>
<body>
    <script>
        function safeFunction() {
            console.log('Safe function called');
        }
        
        let functionName = 'safeFunction';
        
        if (typeof window[functionName] === 'function') {
            window[functionName]();
        } else {
            console.log('Function not found');
        }
    </script>
</body>
</html>

Conclusion

Use window[functionName]() for dynamic function calls in browsers. Avoid eval() due to security risks and always validate function existence before execution.

Updated on: 2026-03-15T22:21:03+05:30

584 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements