Is there a way to check for both `null` and `undefined`?

775,168

Solution 1

Using a juggling-check, you can test both null and undefined in one hit:

if (x == null) {

If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:

if (x === null) {

You can try this with various values using this example:

var a: number;
var b: number = null;

function check(x, name) {
    if (x == null) {
        console.log(name + ' == null');
    }

    if (x === null) {
        console.log(name + ' === null');
    }

    if (typeof x === 'undefined') {
        console.log(name + ' is undefined');
    }
}

check(a, 'a');
check(b, 'b');

Output

"a == null"

"a is undefined"

"b == null"

"b === null"

Solution 2

if( value ) {
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ''
  • 0
  • false

typescript includes javascript rules.

Solution 3

In TypeScript 3.7 we have now Optional chaining and Nullish Coalescing to check null and undefined in the same time, example:

let x = foo?.bar.baz();

this code will check if foo is defined otherwise it will return undefined

old way :

if(foo != null && foo != undefined) {
   x = foo.bar.baz();
} 

this:

let x = (foo === null || foo === undefined) ? undefined : foo.bar();

if (foo && foo.bar && foo.bar.baz) { // ... }

With optional chaining will be:

let x = foo?.bar();

if (foo?.bar?.baz) { // ... }

another new feature is Nullish Coalescing, example:

let x = foo ?? bar(); // return foo if it's not null or undefined otherwise calculate bar

old way:

let x = (foo !== null && foo !== undefined) ?
foo :
bar();

BONUS enter image description here

Solution 4

Does TypeScript has dedicated function or syntax sugar for this

TypeScript fully understands the JavaScript version which is something == null.

TypeScript will correctly rule out both null and undefined with such checks.

More

https://basarat.gitbook.io/typescript/recap/null-undefined

Solution 5

I did different tests on the typescript playground:

http://www.typescriptlang.org/play/

let a;
let b = null;
let c = "";
var output = "";

if (a == null) output += "a is null or undefined\n";
if (b == null) output += "b is null or undefined\n";
if (c == null) output += "c is null or undefined\n";
if (a != null) output += "a is defined\n";
if (b != null) output += "b is defined\n";
if (c != null) output += "c is defined\n";
if (a) output += "a is defined (2nd method)\n";
if (b) output += "b is defined (2nd method)\n";
if (c) output += "c is defined (2nd method)\n";

console.log(output);

gives:

a is null or undefined
b is null or undefined
c is defined

so:

  • checking if (a == null) is right to know if a is null or undefined
  • checking if (a != null) is right to know if a is defined
  • checking if (a) is wrong to know if a is defined
Share:
775,168
David Liu
Author by

David Liu

Updated on July 26, 2022

Comments

  • David Liu
    David Liu almost 2 years

    Since TypeScript is strongly-typed, simply using if () {} to check for null and undefined doesn't sound right.

    Does TypeScript have any dedicated function or syntax sugar for this?

  • David Sherret
    David Sherret over 9 years
    I like doing two equals myVar == null. Just another option.
  • C Snover
    C Snover over 9 years
    == null is the correct way to test for null & undefined. !!something is a useless coercion in a conditional in JS (just use something). !!something will also coerce 0 and '' to false, which is not what you want to do if you are looking for null/undefined.
  • hasen
    hasen about 8 years
    Wouldn't work for numbers because 0 also passes the !foo test.
  • Gingi
    Gingi about 8 years
    Does not work for booleans either, where undefined is different than false. This is very common with optional boolean function parameters, where you should use the common JavaScript approach: function fn(flag?: boolean) { if (typeof flag === "undefined") flag = true; /* set default value */ }
  • kolobok
    kolobok almost 8 years
    What is "juggling-check"?
  • Fenton
    Fenton almost 8 years
    @akapelko it is where the type is juggled (i.e. "can we make this type a boolean"). So an empty string is treated as a boolean false, for example. A common bug when juggling is: "false" == false a non-empty string like "false" evaluates to true.
  • Drenai
    Drenai almost 8 years
    Seems to work ok for booleans: var isTrue; if(isTrue)//skips, if(!isTrue)// enters if(isTrue === undefined)//enters. Also tried it in typescript with var isTrue:boolean which was undefined, and the same if checks. @Gingi, is there something different about what you tried and what I tried?
  • Astravagrant
    Astravagrant over 7 years
    This is due to JS's 'type coercion'.
  • Jon Gunter
    Jon Gunter about 7 years
    Except if x is 0 (and that's a valid value), it will pass your undefined/null test.
  • Fenton
    Fenton almost 7 years
    @JonGunter that would be true of truthy/falsey if(x) style checks, but not if(x == null), which only catches null and undefined. Check it using var c: number = 0; check(c, 'b'); it is not "nully", null, or undefined.
  • Admin
    Admin almost 7 years
    Why would you use the TypeScript playground for this? Nothing here has anything to do with TypeScript.
  • Juangui Jordán
    Juangui Jordán almost 7 years
    Because the question was related to Typescript, I was trying to test different proposed solutions against the Typescript transpiler.
  • Admin
    Admin almost 7 years
    The TS transpiler would not transform any of this code at all.
  • counterflow
    counterflow over 6 years
    What if value is of boolean type?
  • counterflow
    counterflow over 6 years
    And if data is of boolean type?
  • developer
    developer over 6 years
    Is if(!x) equal to if(x == null)?
  • Fenton
    Fenton over 6 years
    @developer - not quite, as if (!x) would treat (for example) the number 0 and the string '' as null, whereas if (x == null) would not.
  • simonhamp
    simonhamp over 6 years
    This is not good test. None of those values are strictly null. Try this: plnkr.co/edit/NfiVnQNes1p8PvXd1fCG?p=preview
  • ARK
    ARK over 6 years
    can you combine two variables eg. if(value1 && value2) to check if both of them are undefined ?
  • ARK
    ARK over 6 years
    can you combine two variables eg. if(value1 && value2) to check if both of them are undefined ?
  • Ramazan Sağır
    Ramazan Sağır over 6 years
    @AkshayrajKore yes you can
  • Alex
    Alex over 6 years
    And now, if I wait a number, and I want to check if this number is not null, but let's say it's value is 0; it does not pass the condition check, so how I do this properly with numbers ?
  • Ramazan Sağır
    Ramazan Sağır over 6 years
    @Alex if the value==0 returns false
  • Alex
    Alex over 6 years
    @RamazanSağır yeah thanks I know that, but the fact is 0 value is something valid that I can have, the only check I want to do is that the variable is neither null or undefined. I have read that I can do it by using val != null (the != instead of !== also checks undefined value)
  • Mark Meuer
    Mark Meuer over 6 years
    How about checking for not null or undefined? Is if ( x!= null) equivalent to if (!(x != null))?
  • Yohan Hirimuthugoda
    Yohan Hirimuthugoda about 6 years
    @RamazanSağır I just checked with one of my piece of code and "if (undefined)" evaluated to true. This is my object { businessId: "undefined" } look like, then if I check "if (businessId)" it is evaluated to true. :(
  • Yohan Hirimuthugoda
    Yohan Hirimuthugoda about 6 years
    @RamazanSağır I found the reason it's because of double quote surrounding undefined keyword. Otherwise if (undefined) evaluated to false;
  • ip_x
    ip_x almost 6 years
    This solution will not work if the tslint rule - "strict-boolean-expressions" is enabled.
  • justcode
    justcode over 5 years
    M. Kamal if something = 0, your verification with !something will give you problems.
  • Ahmed Kamal
    Ahmed Kamal over 5 years
    @arturios can you please give me an example!!
  • justcode
    justcode over 5 years
    @M. Kamal If you are dealing with numbers the 0 will be interpreted as false which is a problem. // In this case the value will be undefined wich is ok var value; if (!value) { console.log("value is false, undefined or empty") } // In this case value is set as 0, this is the problem of using this approach when you deal with number value = 0; if (!value) { console.log("value is false, undefined or empty") }
  • Ahmed Kamal
    Ahmed Kamal over 5 years
    @arturios But 0 is already a falsy value in JavaScript !! so what is the point here?
  • justcode
    justcode over 5 years
    Yes i understand but the question refers only to undefined and null, but now i look that you put the comment of false also.
  • Al-un
    Al-un over 5 years
    For what it's worth: I would have written the update as typeof sth !== 'undefined' && sth !== null. As tests are executed from left to right, I had an error with an undefined sth for the test sth !== null
  • Ahmed Kamal
    Ahmed Kamal over 5 years
    @Al-un nope, see it in action here
  • paul cheung
    paul cheung over 5 years
    so, if someValue is 'false'(with string type), then !!someValue is false(boolean type)?
  • avi.elkharrat
    avi.elkharrat over 5 years
    I guess you may say so.This technic is precisely used to avoid having this kind of confusion. I hope you like it!
  • paul cheung
    paul cheung over 5 years
    but what confused me is !!'false' equals true. Just because of this case, i can not use this technic.
  • avi.elkharrat
    avi.elkharrat over 5 years
    !!'false' is in deed true because 'false' is a valid string
  • paul cheung
    paul cheung over 5 years
    so this technic can not cover this case, or is there a workaround solution?
  • Thomas Poignant
    Thomas Poignant about 5 years
    Why this method are -2 ? Lodash is not good with type script ?
  • Jaider
    Jaider almost 5 years
    the updated version is wrong. The first thing to check should be undefined... like: if(typeof something !== 'undefined' && something !== null){...}
  • tkd_aj
    tkd_aj over 4 years
    This should be the accepted answer now. Typescript 3.7 also supports "Nullish Coalescing". var foo = possibleUndefinedOrNull ?? fallbackValueIfFirstValueIsUndefinedOrNull; Here is the documentation: typescriptlang.org/docs/handbook/release-notes/…
  • Ayfri
    Ayfri about 4 years
    It will evaluate false if value us falsy, as simple as this.
  • carlosvini
    carlosvini about 4 years
    somethingToCompare == (undefined || null). (undefined || null) resolves to null, so it's a loose comparison between somethingToCompare and null
  • KBeDev
    KBeDev about 4 years
    @carlosvini Sure, the point of the comparison is to be verbose and provide a code for reference. That's the reason of the non-strict equals comparison. The purpose of the answer is to be clear and explicative. I'll edit the text to avoid confusion
  • KBeDev
    KBeDev about 4 years
    @ianstigator A boolean can be evaluated as true or false only. If you have a boolean with a null assignation or an undefined value, in both cases the value will be evaluated as false.
  • Dmitry
    Dmitry over 3 years
    Optional chaining and Nullish Coalescing are great but in case of a single if stmt like if (context != null) word.ctx = context; one still has to resort to the old juggling-check as described in the upvoted comment stackoverflow.com/a/28984306/407986
  • CherryDT
    CherryDT over 3 years
    I don't understand what you mean. The code is not verbose or explicit, it is confusing at best and plain wrong at worst. The code a == (b || c) is the not the same as a == b || a == c, instead it will evaluate b || c (in this case to c since b is falsy in your example) and then compare that against a.
  • Totati
    Totati over 3 years
    I wish they added this as an util function.
  • stonedauwg
    stonedauwg over 3 years
    @Fenton I think u meant to say "as falsy" instead of "as null"
  • hien
    hien over 3 years
    Yes, for almost scenarios, we could we Optional chaining , e.g. if (foo?.bar?.baz) typescriptlang.org/docs/handbook/release-notes/…
  • Sindri Þór
    Sindri Þór about 3 years
    Works great here
  • Aleksei
    Aleksei about 3 years
    From the function docs: deprecated since v4.0.0 - use value === null || value === undefined instead.
  • Skrymsli
    Skrymsli almost 3 years
    Is there any practical difference between juggling and type coercion? Why do we need two terms?
  • Fenton
    Fenton almost 3 years
    @Skrymsli it is only "juggling" when the implicit conversion is likely to surprise the programmer (i.e. you have to drop the ball for it to be juggling).
  • Kamafeather
    Kamafeather almost 3 years
    @counterflow then you need to explicitly check for it: if (typeof value == 'boolean')
  • Reactgular
    Reactgular almost 3 years
    You should only use "typeof" if you don't know if a variable is already declared, but this example uses "x" which is declared as a function parameter. So you can just do "x === undefined" instead.
  • Kfir Dadosh
    Kfir Dadosh almost 3 years
    Note that the check for nullish should be defined like this: function isNullish<T>(value: T | undefined | null): value is undefined | null { return <T>value === undefined || <T>value === null; }
  • spierala
    spierala over 2 years
    I believe this is not really a TypeScript thing. This works in Vanilla JS as well. Maybe you could point this out in your answer.
  • Fenton
    Fenton over 2 years
    @Reactgular my test cases cover why that's not the solution.
  • Fenton
    Fenton over 2 years
    @spierala correct, it's just JavaScript.
  • Steven Obua
    Steven Obua over 2 years
    @KfirDadosh is right, isNullish should be used instead, (or call it isNotDefined if you like). The problem with the original code is if the type parameter T is null or undefined, then the original code will return the opposite of the correct answer.
  • refaelio
    refaelio over 2 years
    @Aleksei that's ironic
  • SacredGeometry
    SacredGeometry about 2 years
    Do you mean less concise?
  • blwinters
    blwinters about 2 years
    This should be the accepted answer in 2022
  • vinsinraw
    vinsinraw about 2 years
    Nullish Coalescing seems not supported in typescript 4.5.4. Is it deprecated?
  • vinsinraw
    vinsinraw about 2 years
    Tried const bar = foo ?? 'undefined'; Per Nullish Coalescing, when foo is null or empty, bar should store 'undefined', but I am getting ''. Is it supported in typescript 4.5.4? Via ternary operator it works const bar = foo ? foo : 'undefined';