What is the main advantage of using eval() in JavaScript?

What is the main advantage of using eval() in JavaScript?

Last updated:4/3/2021 6:36:18 AM

1 Answers

Rahul Roi
Rahul Roi

The purpose is to evaluate a string as a Javascript expression. Example:

eval('x = 55');

That 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 you using a dynamic name for a field:

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

This is 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 into the page. 

Note :- You Should Never Use eval() in JavaScript

Where the eval() function is a dangerous function, that executes the code passed with the privileges of the caller. Whenever you want to run eval() function with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage/extension. The most important thing is, the third-party code can see the scope in which the eval() function was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.

After all, the eval() function is also slower than the alternatives since it has to invoke the JavaScript interpreter. Whereas a lot of other constructs are optimized by modern JS engines.

As Example :- 

console.log(eval('2 + 2'));
// expected output: 4
console.log(eval(new String('2 + 2')));
// expected output: 2 + 2
console.log(eval('2 + 2') === eval('4'));
// expected output: true
console.log(eval('2 + 2') === eval(new String('2 + 2')));
// expected output: false

Answer