The eval() function in JavaScript is a built-in function that allows you to evaluate a string of code as if it were a JavaScript statement or block. It takes a single argument, which is the string to be evaluated.
eval(string)
JavaScript eval() function example
A simple example code passes the codeString
variable as an argument to the eval()
function, which evaluates it as if it were a JavaScript expression.
<!DOCTYPE html>
<html>
<body>
<script>
let x = 5;
let y = 10;
let codeString = "x + y";
let result = eval(codeString);
console.log(result)
</script>
</body>
</html>
Output:
Another example
let userCode = "let x = 10; let y = 20; x + y";
let result = eval(userCode); // 30
Comment if you have any doubts or suggestions on this Js basic topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version