In JavaScript, null
is a special singleton object which is helpful for signaling "no value". You can test for it by comparison and, as usual in JavaScript, it's a good practice to use the ===
operator to avoid confusing type coercion:
var a = null;
alert(a === null); // true
As @rynah mentions, "undefined" is a bit confusing in JavaScript. However, it's always safe to test if the typeof(x)
is the string "undefined", even if "x" is not a declared variable:
alert(typeof(x) === 'undefined'); // true
Also, variables can have the "undefined value" if they are not initialized:
var y;
alert(typeof(y) === 'undefined'); // true
Putting it all together, your check should look like this:
if ((typeof(data) !== 'undefined') && (data !== null)) {
// ...
However, since the variable "data" is always defined since it is a formal function parameter, using the "typeof" operator is unnecessary and you can safely compare directly with the "undefined value".
function(data) {
if ((data !== undefined) && (data !== null)) {
// ...
This snippet amounts to saying "if the function was called with an argument which is defined and is not null..."