Is it incorrect to use (type of variable) as condition? es-lint shows Unexpected constant condition

I'm setting up a rest api in Javascript and need to check whether a parameter is a boolean. I can do it using JSON.parse(variable)=='boolean', but this results in an eslint error (no-constant-condition). I can disable the error for this line, but I'm curious if there is a reason not to do so.

I've read the documentation for the error.

A constant expression (for example, a literal) as a test condition might be a typo or development trigger for a specific behavior. For example, the following code looks as if it is not ready for production.

As far as I can tell, it seems like ignoring it is ok.

try { if (!typeof JSON.parse(x) === 'boolean') { throw new Error('x must be boolean'); }
} catch (e) { throw new Error('x must be boolean');
}
1

1 Answer

The no-constant-condition rule is working as expected. Your if statement will always evaluate to false. I'll break down the explination

  1. typeof JSON.parse(x) will return a string of the type (string, number, boolean, etc.)
  2. !SOMETHING will always return a boolean
    1. If SOMETHING is falsy, then !SOMETHING will be true (not false)
    2. If SOMETHING is truthy, then !SOMETHING will be false (not true)

That means you're comparing a boolean(type) to a string (type) with ===. To fix your scenario you need to move the ! (not) to the evaluator

try { if (typeof JSON.parse(x) !== 'boolean') { throw new Error('x must be boolean'); }
} catch (e) { throw new Error('x must be boolean');
}

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like