Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the intended purpose of eval in JavaScript? [duplicate]

Tags:

javascript

Possible Duplicate:
When is JavaScript’s eval() not evil?

I know, generally using eval() is bad practice.

But for what purpose it is existed there?

What is the correct purpose of eval()?

At what situation it is better to use eval()?

like image 819
rajakvk Avatar asked Oct 20 '09 11:10

rajakvk


People also ask

What is the purpose of the eval () method?

The eval() function evaluates JavaScript code represented as a string and returns its completion value.

When should you use eval JavaScript?

If, for your purpose, eval() is faster than manual interpretation, or makes your code simpler, or more clear... then you should use it. If neither, then you shouldn't. Simple as that. One such purpose might be to generate optimized code that would either be too long or too repetitive to write by hand.

What does eval return in JavaScript?

The eval is a part of the JavaScript global object. The return value of eval() is the value of last expression evaluated, if it is empty then it will return undefined .

What is an eval statement?

The eval statement is used to evaluate the value of a variable or a column within a record, and if necessary, convert it into another data type. In stitchers, eval statements are used in combination with OQL to extract values from records in one database and insert those values into another database.


1 Answers

eval() provides access to the JavaScript compiler and this ultimately allows for code to be executed at a later time. The arguments passed to the function are passed to the JavaScript compiler after which the code is executed.

Developers argue about the security of eval(). It is less secure, but if you're absolutely sure your input is sanitized before passing it along, then it shouldn't be a problem.

Also, the results of eval() are generally slower because the code has not yet been compiled nor cached. There's obviously going to be a performance hit for using the function.

It's also difficult to debug code that results from the use of eval() because there is little-to-no contextual information (think line numbers) about the code that is ultimately executed.

In terms of web development, one of the current most popular uses of eval() is to deserialize a JSON string usually in the context of Ajax applications; however, this isn't to say that there aren't many other uses.

like image 116
Tom Avatar answered Sep 26 '22 06:09

Tom