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
typeof JSON.parse(x)will return a string of the type (string,number,boolean, etc.)!SOMETHINGwill always return a boolean- If
SOMETHINGis falsy, then!SOMETHINGwill betrue(not false) - If
SOMETHINGis truthy, then!SOMETHINGwill befalse(not true)
- If
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');
}