The eval() Function

Contact Us or call 1-877-932-8228
The eval() Function

The eval() Function

The reason we are mentioning eval() in this lesson is to acknowledge its existence and to urge you not to use it. We will explain why, but first let's explain what it does.

eval compiles and executes a string containing JavaScript code. It can be a simple expression like "1 + 2" or a long and complex script, with functions and all.

Here's one example that is not too different from what we can find in live sites on the web.

Code Sample:

---- C O D E   O M I T T E D ----

	function getProperty(objectName, propertyName) {
		//expression will be: document.title
		var expression = objectName + "." + propertyName;
		//the eval() function evaluates the expression, so document.title gives us the title of the document
		var propertyValue = eval(expression);
		return propertyValue;
	var prop = "title"; //assume this was given by the user
	alert(getProperty("document", prop)); 
---- C O D E   O M I T T E D ----

This function creates a JavaScript expression by concatenating an object name, with a dot and a property name. Then it uses eval() to evaluate that expression.

As we can see eval() is a powerful function, but it is also potentially dangerous and incredibly inefficient. It's dangerous because it's typically used to evaluate user entered input, which not always is a safe thing to do. It's inefficient because each call to eval() starts a JavaScript compiler.

The use of eval() normally reveals lack of knowledge from the developer that wrote the script. In the example above, we could have used the [ ] accessor for properties. The same effect would be obtained with alert(window[prop]); without having to fire up a compiler just to retrieve the property value.

Remember this: eval is evil. Avoid it as much as you can. If you think you need it, maybe it's because you did not learn yet about an alternative way in JavaScript.