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') .
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' .
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.
Finally, the standard way to check for null and undefined is to compare the variable with null or undefined using the equality operator ( == ). This would work since null == undefined is true in JavaScript. That's all about checking if a variable is null or undefined in JavaScript.
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
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