How to evaluate string mathematical expressions in java script?

950 views Asked by At

Please suggest an alternative to eval() as apparently its "unsafe". Would appreciate an explanation on why as well. I used this code for my calculator app and it works but i would like to optimize it.

if (e.target.innerHTML === "="  ){

    newArr=arr.join(' ');
    var result =eval(newArr);
    pnode.innerHTML = result;
    
}

else
{

    pnode.innerHTML = e.target.innerHTML;
    arr.push(e.target.innerHTML);
    console.log(arr);

}
4

There are 4 answers

0
solanki... On

Instead of using eval() method, we can use objects. Store your data as value in properties with key being identifier of the object.

example :

let obj = {a: 9, b: 10};  
console.log(obj.a +  obj.b); 

OR,

if you need the replacer for eval(), see the below snippet using string which evaluate the sum of 9 and 10 :

console.log(Function('return ' + '9 + 10')())     // 19
0
kriskiller On

Function could help。

const fun = new Function('a', 'b', 'return a + b')
console.log(fun(1, 2)) // output: 3

0
Rubydesic On

The most 'correct' way to do this (that would not be susceptible to something like while(1) {}) is using an expression evaluator library such as MathJS

1
Leaf the Legend On

eval is often considered unsafe because it will run any code it takes as an input on the client's device with full privileges of the caller, regardless of whether that code is malicious or not.
If there is a possibility that the string eval runs could have been affected by a malicious third party, then it is dangerous, as it will have all the permissions your user has granted the webpage.
For example, evil user X might have written a script which your app innocently served to user Y's browser, where it is run with eval.

In your case, however, since you are not serving data from one user to another, there is no possibility that the string could have been affected by a third party, and it is perfectly fine to use eval. See this question. Nevertheless, eval is relatively inefficient compared to the alternative Function. Function, although still unsafe, is more secure, but we have already established that this type of vulnerability does not apply to your use case. More important is the fact that (at least according to the MDN docs), Function is more efficient. Just do: var result = Function("return" + newArr)();.

Your client will still be able to write silly things like while(true){console.log("infinite loop")}, but they could have done this through the console anyway, and it won't affect anyone else. In conclusion, eval and similar functions are often blindly condemned as "unsafe", but this is only true in certain contexts.