Tech Junkie Blog: JavaScript : The eval() Function

Wednesday, April 5, 2017

JavaScript : The eval() Function

The eval() function in JavaScript provides the power of dynamic evaluation, it evaluates a strings of JavaScript codes and returns a value.  If you use the eval on pair of string numbers it will be forgiving and give you the number if it can.  For example if you type int

eval("4+5")  the result will be 9 even though it's a string





Just because you can evaluate numbers that are strings, are you supposed to do it?  It's something you have to consider carefully before you go down that path.

The eval() function takes a one argument a string.  It tries to parse the argument as JavaScript code, if it fails a SyntaxError is thrown.  If it is successful then a value is returned or an undefined is returned if there are no value.  Since eval() uses a lot of interpretation of the code performance can take a hit.

For example if you type in the following code you will get an undefined and a SyntaxError

console.log(eval(myvar));

var myvar = "my variable";


console.log(eval(myvar));





No comments:

Post a Comment