I know there are two methods to determine if a variable exists and not null(false, empty) in javascript:
1) if ( typeof variableName !== 'undefined' && variableName )
2) if ( window.variableName )
which one is more preferred and why?
Answer: Use the typeof operator If you want to check whether a variable has been initialized or defined (i.e. test whether a variable has been declared and assigned a value) you can use the typeof operator.
Say, if a string is empty var name = "" then console. log(! name) returns true . this function will return true if val is empty, null, undefined, false, the number 0 or NaN.
To check if a variable is undefined, you can use comparison operators — the equality operator == or strict equality operator === . If you declare a variable but not assign a value, it will return undefined automatically. Thus, if you try to display the value of such variable, the word "undefined" will be displayed.
We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.
A variable is declared if accessing the variable name will not produce a ReferenceError
. The expression typeof variableName !== 'undefined'
will be false
in only one of two cases:
var variableName
in scope), or undefined
(i.e., the variable's value is not defined)Otherwise, the comparison evaluates to true
.
If you really want to test if a variable is declared or not, you'll need to catch
any ReferenceError
produced by attempts to reference it:
var barIsDeclared = true; try{ bar; } catch(e) { if(e.name == "ReferenceError") { barIsDeclared = false; } }
If you merely want to test if a declared variable's value is neither undefined
nor null
, you can simply test for it:
if (variableName !== undefined && variableName !== null) { ... }
Or equivalently, with a non-strict equality check against null
:
if (variableName != null) { ... }
Both your second example and your right-hand expression in the &&
operation tests if the value is "falsey", i.e., if it coerces to false
in a boolean context. Such values include null
, false
, 0
, and the empty string, not all of which you may want to discard.
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