Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined. Copied!
So the correct way to test undefined variable or property is using the typeof operator, like this: if(typeof myVar === 'undefined') .
When using x === undefined , JavaScript checks if x is a declared variable that is strictly equal to undefined . If you want to check if x is strictly equal to undefined regardless of whether is has been declared or not, you should use typeof x === 'undefined' .
You want the typeof
operator. Specifically:
if (typeof variable !== 'undefined') { // the variable is defined }
The typeof
operator will check if the variable is really undefined.
if (typeof variable === 'undefined') { // variable is undefined }
The typeof
operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
However, do note that typeof null
will return "object"
. We have to be careful to avoid the mistake of initializing a variable to null
. To be safe, this is what we could use instead:
if (typeof variable === 'undefined' || variable === null) { // variable is undefined or null }
For more info on using strict comparison ===
instead of simple equality ==
, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
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