DEV Community

loading...

How to execute a string as command in javascript

raghav9official profile image Raghav Yadav ・Updated on ・1 min read

Ever wondered how to execute string in JavaScript as a command?

Well just use:

var command = "alert('test')";
eval(command); // alerts "test"
Enter fullscreen mode Exit fullscreen mode

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, a third-party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.

eval() is also slower than the alternatives, since it has to invoke the JavaScript interpreter, while many other constructs are optimized by modern JS engines.

AND if you enjoyed the article hit the πŸ’– and that πŸ¦„!

Discussion (4)

Collapse
gaurav5430 profile image
Gaurav Gupta

in most cases, using eval in your production codebase would lead to major security vulnerabilities. do you have a use case where you have to use eval for some reason, or is it more for learning purpose?

Collapse
raghav9official profile image
Raghav Yadav Author • Edited

Eval is dangerous ok nice but it doesn't means that it doesn't have any use.... It was made to serve a purpose.

Collapse
prabhukadode profile image
Prabhu • Edited

But eval function is dangerous .

Collapse
raghav9official profile image
Raghav Yadav Author

Yes it can be in some cases

Forem Open with the Forem app