Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if variable is false and not either true or undefined

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)?

like image 449
Haradzieniec Avatar asked Sep 25 '14 19:09

Haradzieniec


People also ask

Is null == undefined?

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.

Does undefined === false?

The Boolean value of undefined is false.

How do you check if a variable is true in JS?

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 .

How do you check if a variable is undefined or not?

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.


1 Answers

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) { 
like image 140
Quentin Avatar answered Oct 03 '22 19:10

Quentin