0

In JavaScript, we can do this

const someValue = null;
const myVal = someValue ?? "use this string if undefined or null";

and the result is:

console.log(myVal); // "use this string if undefined or null"

Is there a way I can check for null or undefined in an if statement without having to do

if(myVal !== null && myVal !== undefined) {
   // do something
}

? I cannot do a simple truthy check if(myVal){} because zero is a valid value for this variable.

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
snowleopard
  • 781
  • 3
  • 13
  • 36
  • 1
    `null == undefined` so you could look for `something == undefined` or `something != undefined` (or replace those with null). The double equals operator works, but the triple equals operator is strict – Samathingamajig Jun 24 '21 at 20:41
  • if you want also include the case of `""` is simple `if (myVal)` – Eliseo Jun 24 '21 at 20:45
  • 1
    @Eliseo The last sentence in the question explicitly mentions, why `if (myVal)` is not a valid solution in this case ... – derpirscher Jun 24 '21 at 20:49
  • Indeed the answer in this post https://stackoverflow.com/questions/2647867/how-can-i-determine-if-a-variable-is-undefined-or-null myVal == null, is exactly what I was looking for. – snowleopard Jun 25 '21 at 02:13

0 Answers0