How to evaluate a String as a mathematical Expression in JavaScript?

Estimated read time 1 min read

In JavaScript, you can use the eval() function to evaluate a string as a mathematical expression:

const expression = "2 + 3";
const result = eval(expression);
console.log(result);

Note that using eval() can be dangerous as it evaluates any JavaScript code in the string, potentially allowing arbitrary code execution. It’s recommended to use safer alternatives, such as using a library specifically designed for evaluating mathematical expressions, such as mathjs.

Here’s an example using mathjs:

const math = require("mathjs");
const expression = "2 + 3";
const result = math.evaluate(expression);
console.log(result);

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply