I have a string calc, which represents an operation (for example, "2/2")
I want my code to evaluate the string and return the result.
When the string is invalid and cannot be evaluated (for example, "2.2.2", I want to return null.
This is my code so far:
const result = eval(calc);
if (result === undefined){
return null;
} else {
return result;
}
My bug is: when the string is invalid as an operation and cannot be evaluated, I don't get null. Instead, the program throws an error.
How can I get null instead of an error?
try ... catchto catch an error and set your result accordingly