I was wondering, what's the best way to check if something is null or undefined in JSON arrays or objects in general? For years i've been using
if (value !== null && value !== undefined) {
// Value isn't null or undefined
}
I was wondering, what's the best way to check if something is null or undefined in JSON arrays or objects in general? For years i've been using
if (value !== null && value !== undefined) {
// Value isn't null or undefined
}
You can just use the loose equality operator ==
.
It will treat null
and undefined
as if they were the same.
if (value != null) {
/* do something with the value if it isn't null AND undefined */
}
if (value == null) {
/* do something with the value if it is null OR undefined */
}
// Which is the same as this one with the strict equality operator
if (value !== null && value !== undefined) {
/* do something with the value if it isn't null AND undefined */
}
if (value === null || value === undefined) {
/* do something with the value if it is null OR undefined */
}
IMHO using typeof
for undefined
is the safest way, because it does not requires variable to be declared at all. Then you can add value !== null
, so if value
declared, then check that it is not Null
. Of course it depends on your project details, code style etc., and there is no such thing as "best"... But if your environment expects situation, where variables could be not declared or you have some dynamic function generation, keep in mind, that typeof value !== "undefined"
will handle undeclared variables.
if (typeof value !== "undefined" && value !== null) {
console.log("exist and not Null");
} else {
console.log("not exist or Null");
}
Below is the example, which will throw error if not using typeof
:
if (value !== undefined && value !== null) {
console.log("exist and not Null");
} else {
console.log("not exist or Null");
}