In JavaScript highly desirable also undefined
check. You can check null
value and check undefined
type in JavaScript somehow like it:
if ((typeof(x) !== 'undefined') && (x !== null)) {
// ...
}
However, since the variable x
is always defined since it is a formal function parameter, using the typeof
operator is unnecessary and you can safely compare directly with undefined
value:
function fn(x) {
if (x !== undefined && x !== null) {
// ...
}
}
Do check all next way:
x != null
x != undefined
x !== null && x !== undefined
typeof foo === "undefined"
is different from foo === undefined
, never confuse them. typeof foo === "undefined"
is what you really need. Also, use !==
in place of !=
. So the statement can be written as:
function (data) {
if (typeof data !== "undefined" && data !== null) {
// some code here
}
}
You can not use foo === undefined
for undeclared variables.
var t1;
if (typeof t1 === "undefined") {
alert("cp1");
}
if (t1 === undefined) {
alert("cp2");
}
if (typeof t2 === "undefined") {
alert("cp3");
}
if (t2 === undefined) { // fails as t2 is never declared
alert("cp4");
}
var a;
alert(a); // Alerts "undefined"
alert(b); // ReferenceError: b is not defined
a = null;
alert(a === null); // true
alert(typeof(x) === 'undefined'); // true
function test(data) {
if (data != null) {
console.log('Data: ', data);
}
}
test(); // the data=undefined
test(null); // the data=null
test(undefined); // the data=undefined
test(0); // 0
test(false); // false
test('something'); // something