How to calculate string value in JavaScript without using eval?

Sometimes, we want to calculate string value in JavaScript without using eval.

In this article, we’ll look at how to calculate string value in JavaScript without using eval.

How to calculate string value in JavaScript without using eval?

To calculate string value in JavaScript without using eval, we can use the Function constructor.

For instance, we write

const evil = (fn) => {
  return new Function("return " + fn)();
};

console.log(evil("(12 / 5) * 9 + 9.4 * 2;"));

to define the evil function.

In it, we create a function from the fn string with the Function constructor.

fn has the function’s code in a string.

Then we call the function and return its return value.

Next, we call evil with the expression we want to evaluate in a string to get the result of the expression.

Conclusion

To calculate string value in JavaScript without using eval, we can use the Function constructor.