How to Call a JavaScript Function From a String Without Using eval

Share this article

eval
is evil in JavaScript! The MDN eval page states:
Obsolete This feature is obsolete. Although it is still supported by browsers, its usage is discouraged in new projects. Try to avoid using it.
eval executes a string containing code, e.g.
eval("var x = 'Hello from eval!';");
console.log(x);
eval raises several issues:
  1. Security: your string can be injected with other commands by third-party scripts or user input.
  2. Debugging: it’s difficult to debug errors — you have no line numbers or obvious points of failure.
  3. Optimization: the JavaScript interpreter cannot necessarily pre-compile the code because it could change. While interpreters have become increasingly efficient, it’ll almost certainly run slower than native code.
Unfortunately, eval is very powerful and it’s easy for less experienced developers to overuse the command. Despite the warnings, eval still works — even in Strict Mode — but you can normally avoid it. In the past it was primarily used for de-serializing JSON strings but we now have the safer JSON.parse
method. However, what if we have a function name in a string, e.g.
// function we want to run
var fnstring = "runMe";

function runMe() {
	// do stuff
}
How do we execute the runMe() function without using eval? I recently encountered this situation when using the HTML5 History API; the pushState method won’t permit you to store a direct reference to a function so you need to define its name as a string. You could also face similar challenges using Web Workers or any other API where objects are serialized. The simplest and safest execution-without-eval solution is a range of conditions, e.g.
// function we want to run
var fnstring = "runMe";

switch (fnstring) {
	case "functionX": functionX(); break;
	case "functionY": functionY(); break;
	case "functionZ": functionZ(); break;
	case "runMe": runMe(); break;
}
It’s safe, but fairly inefficient and painful to write if you have dozens of possible function calls. A better solution is to use the window object which references the current window and all items within it. We can check whether fnstring is available as an object within window
and run it if it’s a function, e.g.
// function we want to run
var fnstring = "runMe";

// find object
var fn = window[fnstring];

// is object a function?
if (typeof fn === "function") fn();
You can perform other checks if necessary to ensure the function has an expected name. What if the function we want to call has parameters — perhaps stored in an array? No problem; we simply use the apply method:
// function name and parameters to pass
var fnstring = "runMe";
var fnparams = [1, 2, 3];

// find object
var fn = window[fnstring];

// is object a function?
if (typeof fn === "function") fn.apply(null, fnparams);
So that’s another reason to stop using eval. As a bonus, this solution is safer, less error prone, easier to debug and will normally execute faster. I hope it helps.

FAQs on Executing JavaScript Functions from Strings Without eval

What is the significance of calling a JavaScript function with a string without using eval()?

The eval() function in JavaScript is a powerful tool that allows you to execute arbitrary strings of code. However, it’s often considered a bad practice to use eval() due to security and performance issues. It can potentially open up your code for injection attacks. Moreover, modern JavaScript engines optimize the performance of your code, but they can’t do this with code executed by eval(). Therefore, it’s beneficial to know how to call a JavaScript function with a string without using eval(). This can be achieved by using the window object or the Function constructor, which are safer and more efficient alternatives.

How can I use the window object to call a JavaScript function with a string?

The window object in JavaScript represents the window in which the browser is displayed. It’s the global object in the browser environment, and all global variables and functions become properties and methods of the window object. You can use the window object to call a function with a string by accessing the function as a property of the window object. Here’s an example:

function hello() {
console.log("Hello, world!");
}

var functionName = "hello";
window[functionName](); // Outputs: "Hello, world!"

In this code, “hello” is a property of the window object that refers to the hello() function. So, window“hello” calls the hello() function.

What is the Function constructor and how can it be used to call a function with a string?

The Function constructor in JavaScript creates a new Function object. It’s a less common but still valid way to define a function. You can use the Function constructor to call a function with a string by passing the string to the constructor. Here’s an example:

var sum = new Function('a', 'b', 'return a + b');

console.log(sum(1, 2)); // Outputs: 3

In this code, the Function constructor creates a new function that takes two arguments, ‘a’ and ‘b’, and returns their sum. The arguments and the function body are passed as strings.

Can I call a function with a string if the function is a method of an object?

Yes, you can call a function with a string even if the function is a method of an object. You can do this by accessing the method as a property of the object, similar to how you would do it with the window object. Here’s an example:

var obj = {
hello: function() {
console.log("Hello, world!");
}
};

var methodName = "hello";
obj[methodName](); // Outputs: "Hello, world!"

In this code, “hello” is a property of the obj object that refers to the hello() method. So, obj“hello” calls the hello() method.

What are the limitations of calling a JavaScript function with a string?

While calling a JavaScript function with a string can be useful in certain situations, it has some limitations. One limitation is that it only works with global functions or methods of known objects. If the function is not a property of a known object, you can’t call it with a string. Another limitation is that you can’t directly pass arguments to the function. If the function takes arguments, you need to include them in the string or use an additional function to pass them. Despite these limitations, calling a function with a string can be a powerful tool when used correctly.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

evalevaluationjavascriptoptimization
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week