View Full Version : Calling a js function when name is stored in a variable

06-17-2008, 06:22 PM
I have a function name stored in a variable - how do I call the function?

Philip M
06-17-2008, 06:35 PM

var test = "functionName";
eval(test + '()');

06-17-2008, 07:32 PM
If the function is a global function, use window.

function succ(x) {
return x + 1;

var str = "succ";

var a = succ(1);
var b = window["succ"](2);
var c = window[str](3);

var f = window["succ"];
var d = f(4);

06-17-2008, 07:32 PM
Is it a global function? If so, then you can do window[name]();. If it's a local function, you need to use eval(name)(); or eval(name+'()'); like Philip M suggests.

06-17-2008, 07:41 PM
um... whats the difference between a local and global function?

06-17-2008, 07:42 PM
Edit: A local function is a function defined within another function.

I have no idea if this is a bad idea or not (I just thought of it), but for local functions, you can avoid eval for them if you attach them to a variable that denotes the local scope:

function f() {
var g = function() {
var local = {
g: g
var str = "g";

06-17-2008, 09:25 PM
huh. Didn't know you could define functions within functions. I guess mine would be a global function then heh.

06-18-2008, 11:27 AM
I have a function name stored in a variable - how do I call the function? Subscribed and saved this thread for reference :)
Good question and many thanks :thumbsup:

Philip M
06-18-2008, 01:26 PM
Thanks all round - except for the guy who provide the answer! :p:p