Reputation: 896
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?
Upvotes: 1
Views: 181
Reputation: 1218
eval() will return an error when it cannot parse the command correctly. When you use try and catch you can return null when an error occurred.
try{
const result = eval(calc);
return result;
}
catch (error){
return null;
}
Upvotes: 1
Reputation: 13222
Using eval()
is often not necessary and can lead to security and performance problems. There is likely a better solution available. I advise you to explain your use case more detailed so we can help you find a better solution.
If you really want to do this you can use a try catch statement since an exception will be thrown when the code can't be evaluated.
console.log(myEval("2.2.2"));
console.log(myEval("2/2"));
function myEval(str) {
try {
return eval(str);
} catch {
return null
}
}
Upvotes: 2
Reputation: 406
Use try/catch
try {
result = eval(calc);
return result;
} catch (e) {
return null;
}
Upvotes: 3