Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
JavaScript eval() function
3.
Syntax of eval() in Javascript
3.1.
Javascript
3.2.
Parameters 
4.
Examples of the Eval Function
4.1.
To Call a Function
4.2.
Javascript
4.3.
To Pass an Object as an Argument
4.4.
Javascript
4.5.
Using Eval Function with JavaScript Statements
4.6.
Javascript
4.7.
Use Eval Function with a JSON Object
4.8.
Javascript
5.
Disadvantages of using Eval
6.
Frequently Asked Questions
6.1.
What is the JavaScript eval function?
6.2.
What is the parameter of the eval function?
6.3.
What does the eval function return in JavaScript?
6.4.
Can the eval function modify the global scope in JavaScript?
6.5.
Can the eval function improve the performance of the code in JavaScript?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

JavaScript eval() function

Author Rishabh
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

JavaScript eval function is used to execute a string that contains a JavaScript expression. We also use the JavaScript eval function to execute one or more JavaScript statements.

javascript eval function

Let’s look at the working of the JavaScript eval function.

JavaScript eval() function

JavaScript's eval() function dynamically executes code stored as a string. It takes a string argument, runs the code, and returns the result. It operates globally, may have performance drawbacks, and can pose security risks if used with untrusted code. It's best to avoid eval() in favor of safer coding practices.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax of eval() in Javascript

Now let’s look at the syntax for the JavaScript eval function

  • Javascript

Javascript

// Using the eval function
const ans = eval("4+4");
console.log(ans);

Parameters 

The function eval accepts a string with a “” symbol. It can be an expression, or a statement or a sequence of statements.
 

Output 

8

 

Explanation 

The output for an eval function is the output of the expression. Here as we can calculate 4+4 is 8. Therefore, eval function returns 8 as the output. If the input is a statement, then the output will be a statement. If there is no calculated value, then undefined is returned.

Examples of the Eval Function

Here we will discuss some of the examples to understand the eval function of JavaScript 

To Call a Function

Example 1 - Let us see how to pass a function as an argument inside the eval function.

  • Javascript

Javascript

// Defining a function
function add(x, y) {
   return (x + y);
}

// Variable to store the answer
let ans;

// Using the eval() function
ans = eval("add(7, 4)");

// Displaying the result
console.log(ans);


Output

11

 

Explanation

In the code above, we passed a function with two arguments that adds the parameters x and y and stores the answer in the ‘ans’ variable. Now the eval function is called for 7 and 4 as inputs and therefore 11 is returned as the output.

To Pass an Object as an Argument

Example 2 - Now let’s use JavaScript eval function to pass an object as an argument and then use the eval function to evaluate the expression.

  • Javascript

Javascript

// Using the eval function 
console.log(eval(new String('2 + 1')));


Output 

[String: '2 + 1']


Explanation

In the code, we passed a string object into the eval function, and because we passed a string object, it printed “2+1”.

Using Eval Function with JavaScript Statements

Example 3 - Now, we will use the eval function to execute the if-else statement.

  • Javascript

Javascript

// Create variables
let marks = 93;
let state;

// If else condition inside the string
state = "if(marks >= 80 && marks <= 100) {'You got A grade';} else {'You got B grade';}"

// Output
console.log(eval(state));


Output 

You got A grade

 

Explanation

In the code, we run a conditional statement in the string. Since the mark is 93, “You got A grade” is printed as the output.

Use Eval Function with a JSON Object

Example 4 - Using JavaScript eval function to execute the string as JavaScript code and convert it to a JavaScript object.

  • Javascript

Javascript

// Create a variable
let obj;

// Create an object string
obj = "({'country': ['Japan', 'Bangladesh'], 'capital': ['Tokyo', 'Dhaka']})";

// Use eval() function to convert string to a JS object
const res = eval(obj);

// Print the output
console.log("The capital of", res.country[0], "is",res.capital[0]);


Output 

The capital of Japan is Tokyo


Explanation

In the code, the string obj contains data in the form of a JSON object. Now after storing this JSON object in a variable res, we will be able to access the properties of the object.

Disadvantages of using Eval

  1. The eval function can execute any type of code, including malicious code that can compromise the security of your system. For example, attackers may steal sensitive data.
     
  2. The eval function can be slow for large amounts of code.

Frequently Asked Questions

What is the JavaScript eval function?

The JavaScript eval function is a built-in function in JavaScript that executes a string of code. 

What is the parameter of the eval function?

A String is a parameter of the eval function.

What does the eval function return in JavaScript?

The eval function returns the value of the code given as an argument.

Can the eval function modify the global scope in JavaScript?

Yes, the eval function can modify the global scope in JavaScript as it can change variables in the global scope.

Can the eval function improve the performance of the code in JavaScript?

No, the javaScript eval function can slow down the performance of the code in JavaScript. 

Conclusion

In this article, we discussed the JavaScript eval function. You can also read the article An Introduction to JavaScript to improve your knowledge about javascript.

To learn more, check out our articles:

And many more on our platform Coding Ninjas Studio.

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Previous article
Method Chaining
Next article
Generator Function in JavaScript
Live masterclass