What’s the best way to check if myvar
javascript variable === false
or not (it may be undefined as well).
JavaScript
x
2
1
if (myvar === false)
2
would be fine but myvar
it could be undefined. Only false
value is acceptable, not undefined.
Any shorter than if (typeof myvar !== "undefined" && myvar === false)
?
Advertisement
Answer
If the variable is declared then:
JavaScript
1
2
1
if (myvar === false) {
2
will work fine. ===
won’t consider false
to be undefined.
If it is undefined
and undeclared then you should check its type before trying to use it (otherwise you will get a reference error).
JavaScript
1
2
1
if(typeof myvar === 'boolean' && myvar === false) {
2
That said, you should ensure that the variable is always declared if you plan to try to use it.
JavaScript
1
6
1
var myvar;
2
// ...
3
// some code that may or may not assign a value to myvar
4
// ...
5
if (myvar === false) {
6