learningjavascriptks learningjavascriptks - 1 month ago 6
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

eval
if it is
false
? on the console:

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


unlike
Boolean(2+2)
<-- returns
true
. Help?

Answer

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 {
    eval('2+2(9.1-)9');
    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.

Comments