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);
}
Instead of using
eval()
method, we can use objects. Store your data asvalue
in properties withkey
being identifier of the object.example :
OR,
if you need the replacer for
eval()
, see the below snippet using string which evaluate the sum of9
and10
: