In javascript language, null is a special object. When you declare a variable and do not assign any value to it, the following evaluation will return true:
var a;
if(a == null) alert("a is null");
if(!a) alert("!a is true");
You will see both alert boxes.
However, if there is no variable a defined in your javascript function, the evaluations above will cause a javascript error. To avoid the javascript error, you should use the following statement to check if the variable is defined or not:
// a is not defined anywhere in your javascript
// if(!a) will throw an exception
// if(a == null) will also throw an exception
// following statement will show the alert box
if(typeof(a) == 'undefined') alert("variable a is not defined yet");
var a;
if(a == null) alert("a is null");
if(!a) alert("!a is true");
You will see both alert boxes.
However, if there is no variable a defined in your javascript function, the evaluations above will cause a javascript error. To avoid the javascript error, you should use the following statement to check if the variable is defined or not:
// a is not defined anywhere in your javascript
// if(!a) will throw an exception
// if(a == null) will also throw an exception
// following statement will show the alert box
if(typeof(a) == 'undefined') alert("variable a is not defined yet");
Comments