1

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?

1
  • 2
    First, please avoid using eval ( see here why). Secondly use a proper try ... catch to catch an error and set your result accordingly Commented Aug 17, 2020 at 9:38

3 Answers 3

3

Use try/catch

try {
    result = eval(calc);
    return result;
} catch (e) {
    return null;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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
  }
}

Comments

1

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.