Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the main benefit of using eval() in JavaScript?

I know this may be a newbie question, but I'm curious as to the main benefit of eval() - where would it be used best? I appreciate any info.

like image 526
Caffeinated Avatar asked May 06 '12 21:05

Caffeinated


People also ask

What is the purpose of using eval )?

Eval function is mostly used in situations or applications which need to evaluate mathematical expressions. Also if the user wants to evaluate the string into code then can use eval function, because eval function evaluates the string expression and returns the integer as a result.

When should you use eval JavaScript?

Definition and Usage The eval() method 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.

What is the use of eval () function give example?

Definition and Usage The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.

Is eval good in JavaScript?

It is a possible security risk, it has a different scope of execution, and is quite inefficient, as it creates an entirely new scripting environment for the execution of the code. See here for some more info: eval. It is quite useful, though, and used with moderation can add a lot of good functionality.


1 Answers

The eval function is best used: Never.

It's purpose is to evaluate a string as a Javascript expression. Example:

eval('x = 42'); 

It has been used a lot before, because a lot of people didn't know how to write the proper code for what they wanted to do. For example when using a dynamic name for a field:

eval('document.frm.'+frmName).value = text; 

The proper way to do that would be:

document.frm[frmName].value = text; 

As the eval method executes the string as code, every time that it is used is a potential opening for someone to inject harmful code in the page. See cross-site scripting.

There are a few legitimate uses for the eval function. It's however not likely that you will ever be in a situation where you actually will need it.

like image 100
Guffa Avatar answered Sep 19 '22 18:09

Guffa