Monday, 8 July 2013

Don't eval(Javascript)

I was looping through the Department data-departmentVO_1 to departmentVO_5 (each contained DepartmentVO complexType's object) and display info against the respective department.

for ( var x = 1; x < 5; x++) {

   var info = "departmentVO_"+x;

   var department =;



Surprisingly javascript was throwing error for department being undefined. That indicated was not working as I expected.

I searched for concatenating loop variable to access a variable in javascript and found out that something on this line would work:

eval('var department = ';

w3schools says: The eval() function evaluates or executes an argument.
If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.

But misuse of eval has led to serious concerns like security issues or performance issue or often simple bugs. Also each invocation of eval() creates a new instance of the JavaScript interpreter and hence creation of new execution context. In short additional resource being put to use. Plus such code is harder to debug and maintain (Reminds me of 'goto' statement...we can still use it, but difficult to find problems). So it is better to check if there is any better, neater and safer alternative.

I decided not to use eval in my case. Understanding what I was trying to obtain, I realized that square brackets can be used instead of literal dot-names. So my code:

var department =;

replaced with

var department = data[info];

I'm convinced, so lets use eval with care!

No comments:

Post a Comment