-->

How to Call a JavaScript Function From a String - Javascript Tricks

How do I execute a JavaScript function when I have its name as a string?
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:
Security: your string can be injected with other commands by third-party scripts or user input. Debugging: it’s difficult to debug errors — you have no line numbers or obvious points of failure. 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.

reference: https://www.sitepoint.com/call-javascript-function-string-without-using-eval/

question: How do I execute a JavaScript function when I have its name as a string?



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.

You may like these posts

  1. To insert a code use <i rel="pre">code_here</i>
  2. To insert a quote use <b rel="quote">your_qoute</b>
  3. To insert a picture use <i rel="image">url_image_here</i>