Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
82
rated 0 times [  88] [ 6]  / answers: 1 / hits: 95590  / 10 Years ago, thu, september 25, 2014, 12:00:00

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


More From » variables

 Answers
9

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

[#69335] Tuesday, September 23, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynnb

Total Points: 402
Total Questions: 96
Total Answers: 109

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
kaitlynnb questions
;