---
title: "What is the main advantage of using eval() in JavaScript?"  
description: "What is the main advantage of using eval() in JavaScript?"  
author: "Anonymous User"  
published: 2021-04-03  
updated: 2021-04-03  
canonical: https://www.mindstick.com/forum/156431/what-is-the-main-advantage-of-using-eval-in-javascript  
category: "javascript"  
tags: ["javascript", "scripting"]  
reading_time: 2 minutes  

---

# What is the main advantage of using eval() in JavaScript?

What is the main advantage of using [eval](https://www.mindstick.com/forum/2167/inline-coding-one-more-eval-merge)() in [JavaScript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript)?

## Replies

### Reply by 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: 4console.log(eval(new String('2 + 2')));// expected output: 2 + 2console.log(eval('2 + 2') === eval('4'));// expected output: trueconsole.log(eval('2 + 2') === eval(new String('2 + 2')));// expected output: false
```


---

Original Source: https://www.mindstick.com/forum/156431/what-is-the-main-advantage-of-using-eval-in-javascript

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
