JavaScript eval() method can execute a statement, expression, or a group of statements and return its completion value if it exists or undefined if there is no completion value.
In simple words, if the parameter is an expression then it will be evaluated and the value will be returned but if the parameter is a statement or multiple statements then it will be executed and the method will return undefined unless the final statement has a completion value.
JavaScript eval() Function Syntax
The eval() is a method of the JavaScript global object that can be directly called anywhere using the below syntax.
eval(string)
Parameter:
This method takes a single parameter, which is a string. This string can contain a statement, an expression, or a sequence of statements. It can also contain JavaScript code to be evaluated.
Return:
This method returns the completion value and if there is no completion value it will return undefined.
Also Read: Introducing Object.groupBy() and Map.groupBy() in JavaScript
Examples of eval() Function
Let’s see some simple examples to demonstrate the use of eval in JavaScript.
Example 1: Evaluate Expression
The below script contains a string that contains a JavaScript expression. Let’s evaluate it using the eval() method and print the output in the console.
const exp = "2 + 2";
const result = eval(exp);
console.log(result);
Output:
4
Here you can see that the expression is successfully evaluated and the eval() method returned the result.
Example 2: Execute Statement
This time the string contains a JavaScript statement to print “Hello World” in the console, let’s try to input it in the eval() method.
const sta = 'console.log("Hello World")'
const result = eval(sta);
console.log(result);
Output:
Hello World
undefined
Here you can see that the statement inside the string is successfully executed as we have gotten the “Hello World” in the console but we also have undefined in the output. This is because the last statement has no completion value and we know that when there is no value to return, eval() returns undefined.
Example 3: Execute Multiple Statements
Let’s evaluate a group of statements using the eval() method.
const stas = `let a = 2;
let b = 3;
let sum = a + b;
console.log("Sum is: " + sum);
`;
eval(stas);
Output:
Sum is: 5
The output is correct as 2 + 3 is 5, which means all the statements are successfully executed. We have not got an undefined here as we have not tried to print the value that eval() returns, if we print it then again we will get undefined.
Evaluating a Function Using eval()
Directly passing a function inside a string to be evaluated using the eval() method will cause an error.
Example:
Let’s try to pass a function declaration inside the string to evaluate it using the eval() method.
const fun = "function sum(a, b) { return a + b; }";
const getFun = eval(fun);
console.log(getFun(2, 3)); // undefined
Output:
console.log(getFun(2, 3)); // undefined
^
TypeError: getFun is not a function
at Object.<anonymous> (C:\Users\ag290\OneDrive\Desktop\eval\app.js:27:13)
at Module._compile (internal/modules/cjs/loader.js:759:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)
at Module.load (internal/modules/cjs/loader.js:628:32)
at Function.Module._load (internal/modules/cjs/loader.js:555:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:826:10)
at internal/main/run_main_module.js:17:11
Here we got an error.
To evaluate a string containing a function using the eval() method, it is required to wrap it properly in a round bracket ():
const fun = "(function sum(a, b) { return a + b; })";
const getFun = eval(fun);
console.log(getFun(2, 3)); // 5
Output:
5
Here we got the expected result, so next time you try it, don’t forget to wrap your function inside (), before executing it.
Avoid Using eval()
In the early days of JavaScript, eval() might have been a good choice for dynamic code execution. But in modern JavaScript, it is not advisable to use eval().
Using eval() can cause security issues as it can run malicious code inside your system without permission, also it can access the outer variable which can be tempered and create trouble in the expected execution of the application so be careful when using eval.
Instead, you can use alternatives like template literals and function constructors that execute codes more safely and efficiently.
Summary
Eval means evaluate, as the name suggests, the eval() function in JavaScript is used to evaluate an expression present in a string passed as an argument and return the completion value, if the completion value does not exist then it returns undefined. Executing JS code inside the eval() method might not be a good idea as it can temper external variables and also possible that you mistakenly executed malicious code which can cause damage to your system.
Read More: NodeJS Keywords – What Are Reserved Keywords in NodeJS?
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval