Using Javascript eval function


Javascript eval function

Long, long in the past, I was trying to obtain a logical expression from some different variables and concatenate them into one single variable, to use that further for a jQuery plugin. Everything looked great when running console.log(myVar), but then the problem came. In my mind, I didn’t thought that the result would be a string, and not an expression, and I cannot use that further in my validation.

Function eval() to the rescue

The eval() function evaluates or executes an argument. Basically, you give a string as an argument in this function, and then it is evaluated as an expression.



Let’s see an example:

This is very useful when you want to evaluate expressions, or if you like more this other exposure: To transform functions, variables or other things that are written as strings into javascript expression that are not strings, and can be evaluated.

The eval() function is supported in all major browsers.

Beware! eval can be evil

The eval function gives you access to javascript’s compiler. This can be a huge security risk because it grants far too much power to the passed in text. Avoid this function if you cannot trust 100% the strings that you are passing to it (eg: strings from the DOM, or strings passed by users, etc…).


A problem with eval() is its performance. In older browsers, you encountered a double interpretation from the browser, which means that your code is interpreted and the code inside the eval() is interpreted also. The result could be ten times slower in some browsers.


Although this is a good tool for evaluating strings as expressions in javascript, you should be aware of it’s performance and vulnerability problems when you use it in your projects.

That’s it for now, see you in our next article!

Request an article ←