As a follow-up to this question: Is there ever a reason to write "if (myBoolean == true)" in a JavaScript conditional? –
Why is it good practice to use if (myBoolean === true) in JavaScript? As a relatively inexperienced JavaScript user, I’m trying to work out in what specific, real-world scenarios you’d end up with a value that might be a Boolean true or might be a “truthy” value, so that you would need to check if (myBoolean === true) rather than if (myBoolean)
I’ll challenge the premise of the question: I don’t think it’s good practice, nor do I think there’s a general consensus that it is. 🙂
The only reason for using
=== truewould be if you weren’t sure thatmyBooleanwas actually a boolean and you wanted the result to be false if it weren’t. There are use cases for that, but they’re quite limited. 99.9% of the time, simplyif (myBoolean)suffices, even though it will be true for1,"foo", and other truthy values.There are times when using strict equality for other reasons is quite a good idea, because JavaScript’s rules for loose equality if the operands are of different types are quite complex. But if you’re using something as a flag, there’s little if any point to using
===on it.One particular place where I’ve seen
===used with boolean values is in code inspired by jQuery, where a callback function can cancel an action by returningfalse, but doesn’t have to return anything. When a function has no explicit return value, the result of calling that function isundefined, which is, of course, falsey. So code that wants to check whether the function returnedfalse, not justundefined, would do this:But that’s a relatively infrequent use case, and of course it involves
=== falseas opposed to=== true…