I was following the below logic to check if a variable is undefined or not:
if (variable==undefined){
////implementation
}
But found that for some cases it did not function as expected. So, tried this approach,
if(typeof(variable) == "undefined"){
/////implementation
}
So which one is most reliable?
The typeof operator for undefined value returns undefined . Hence, you can check the undefined value using typeof operator. Also, null values are checked using the === operator. Note: We cannot use the typeof operator for null as it returns object .
Note: The undefined is not a reserved keyword in JavaScript, and thus it is possible to declare a variable with the name undefined. So the correct way to test undefined variable or property is using the typeof operator, like this: if(typeof myVar === 'undefined') .
Simply put, undefined means a variable has been declared but has not yet been assigned a value. undefined is a type by itself (undefined). Unassigned variables are initialized by JavaScript with a default value of undefined.
You will get undefined value when you call a non-existent property or method of an object. In the above example, a function Sum does not return any result but still we try to assign its resulted value to a variable. So in this case, result will be undefined.
Your second way is the most reliable but you don't need the parenthesis for the typeof
operator. See this question.
if (variableName){
////implementation
}
this way is more use full than second option
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