What's the best way to check if myvar
javascript variable === false
or not (it may be undefined as well).
if (myvar === false)
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)
?
It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.
The Boolean value of undefined is false.
Use the strict equality (===) operator to check if a variable is equal to true - myVar === true . The strict equality operator will return true if the variable is equal to true , otherwise it will return false .
Answer: Use the equality operator ( == )In JavaScript if a variable has been declared, but has not been assigned a value, is automatically assigned the value undefined . Therefore, if you try to display the value of such variable, the word "undefined" will be displayed.
If the variable is declared then:
if (myvar === false) {
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).
if(typeof myvar === 'boolean' && myvar === false) {
That said, you should ensure that the variable is always declared if you plan to try to use it.
var myvar; // ... // some code that may or may not assign a value to myvar // ... if (myvar === false) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With