Rules

Secret ingredients to quality software

Edit
Info

Do you know not to use the "eval" function?

Last updated by William Yin on 24 Aug 2015 01:08 am (over 5 years ago) See History

The Javascript command "eval" evaluates the content of a text string and then runs it as Javascript code. It's common to see it around, however "eval" is one of the most inefficient constructs that JavaScript has. There are always more efficient ways to code and get a direct reference.

Most of people that use "eval" want part of a variable name to be variable.

Once you realize that all global variables are held in the window array it becomes rather obvious that you can refer to that same field name without needing to use "eval" by referring to it.

eval('somevar' + num)

Figure: Bad example - The developer creates the variable name by concatenating the constant and variable parts together

window['somevar' + num]

Figure: Good example - Referencing the same field is as simple to code and more efficient than using "eval"

Tiago AraujoTiago Araujo

We open source. This page is on GitHub