JavaScript eval alternatives are the Arrow function, Math object, and Parser library. These are evaluated an expressions in JavaScript without using the eval
function.
JavaScript eval alternative example
Simple example code evaluates expression without eval in JavaScript.
Arrow function: You can use an arrow function with the Function
constructor to evaluate an expression.
const expression = "1 + 2";
const result = new Function(`return ${expression}`)();
console.log(result);
Output: 3
Math object: If your expression consists of mathematical operations, you can use the Math
object to evaluate it.
const expression = "1 + 2 * 3";
const result = eval(expression);
console.log(result);
Output: 7
Parser library: You can use a parser library like mathjs
or jsep
to parse and evaluate expressions. For example:
<!DOCTYPE html>
<html>
<head>
<title>Math Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.5.0/math.min.js"></script>
<script>
const expression = "1 + 2 * 3";
const result = math.evaluate(expression);
console.log(result);
</script>
</head>
<body>
<!-- Your HTML code here -->
</body>
</html>
Output:
Do comment if you have any doubts or suggestions for this JS topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version