learningjavascriptks learningjavascriptks - 8 months ago 106
Javascript Question

How do I check the Boolean value on eval() or if an arithmetic operation is false?

I am doing this for a calculator project, I want to check if the operation is valid or not, somehow I cannot check for the Boolean value of

if it is
? on the console:

Boolean(2+2(9.1-)9); // Both operations return unexpected token

<-- returns
. Help?


If I understood your question correctly, the only thing you want to know is "Is that a valid expression". One very simple way to check this is using eval() as you did here, and to enclose it in a try, and see if any error occurs. For example, you could write this :

try {
    valid = true;
} catch (e) {
    valid = false;

Then, the variable valid contains true if the expression is valid, and false if it is not.

Warning with eval() though : Every valid code will pass this test, not only mathematical expressions : Plus, that code will be executed. Be careful what strings you give it.