-2

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
}

2 Answers2

1

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 */
}
Xion 14
  • 427
  • 2
  • 8
-1

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");
}
tarkh
  • 2,424
  • 1
  • 9
  • 12
  • 1
    @T.J.Crowder, ah, sorry) I mean exactly what you wrote, but lost focus. Fixed. About answers - I agree, stackoverflow needs some feature with merging questions. Anyway thanx for pointing this out. – tarkh Sep 10 '22 at 12:10
  • I would expect to get an error if I forgot to declare a variable – Konrad Sep 10 '22 at 13:30
  • so... which one is the best? – sda dsasdsa Sep 10 '22 at 14:13
  • @sdadsasdsa, 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. – tarkh Sep 10 '22 at 14:45