function someFunc() { return 'Hello, world'; }
function call(funcName) { eval(funcName + '()'); }
console.log(call('someFunc'));
But console.log
doesn't print 'Hello world'. How can I return value after eval
function?
function someFunc() { return 'Hello, world'; }
function call(funcName) { eval(funcName + '()'); }
console.log(call('someFunc'));
But console.log
doesn't print 'Hello world'. How can I return value after eval
function?
You want:
call(funcName) { window[funcName](); }
And don't use the void
keyword. It ignores return values and always returns undefined from a statement.
To answer your question using eval :
function someFunc() { return 'Hello, world'; }
function call(funcName) { return eval(funcName + '()'); }
console.log(call('someFunc'));
And you can use eval if you trust the input. this is the rule of thumb
Don't use eval
-- it's evil. Why don't you try this:
Get JavaScript function-object from its name as a string?
After getting a reference to the function, you can simply call it and use the return value directly.