Is there a way to check for both `null` and `undefined`?
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();
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
David Liu
Updated on July 26, 2022Comments
-
David Liu almost 2 years
Since TypeScript is strongly-typed, simply using
if () {}
to check fornull
andundefined
doesn't sound right.Does TypeScript have any dedicated function or syntax sugar for this?
-
David Sherret over 9 yearsI like doing two equals
myVar == null
. Just another option. -
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 usesomething
).!!something
will also coerce 0 and '' to false, which is not what you want to do if you are looking for null/undefined. -
hasen about 8 yearsWouldn't work for numbers because
0
also passes the!foo
test. -
Gingi about 8 yearsDoes not work for booleans either, where
undefined
is different thanfalse
. 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 almost 8 yearsWhat is "juggling-check"?
-
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 totrue
. -
Drenai almost 8 yearsSeems to work ok for booleans:
var isTrue; if(isTrue)//skips, if(!isTrue)// enters if(isTrue === undefined)//enters
. Also tried it in typescript withvar isTrue:boolean
which was undefined, and the same if checks. @Gingi, is there something different about what you tried and what I tried? -
Astravagrant over 7 yearsThis is due to JS's 'type coercion'.
-
Jon Gunter about 7 yearsExcept if x is 0 (and that's a valid value), it will pass your undefined/null test.
-
Fenton almost 7 years@JonGunter that would be true of truthy/falsey
if(x)
style checks, but notif(x == null)
, which only catchesnull
andundefined
. Check it usingvar c: number = 0; check(c, 'b');
it is not "nully",null
, orundefined
. -
Admin almost 7 yearsWhy would you use the TypeScript playground for this? Nothing here has anything to do with TypeScript.
-
Juangui Jordán almost 7 yearsBecause the question was related to Typescript, I was trying to test different proposed solutions against the Typescript transpiler.
-
Admin almost 7 yearsThe TS transpiler would not transform any of this code at all.
-
counterflow over 6 yearsWhat if value is of boolean type?
-
counterflow over 6 yearsAnd if data is of boolean type?
-
developer over 6 yearsIs if(!x) equal to if(x == null)?
-
Fenton over 6 years@developer - not quite, as
if (!x)
would treat (for example) the number0
and the string''
as null, whereasif (x == null)
would not. -
simonhamp over 6 yearsThis is not good test. None of those values are strictly
null
. Try this: plnkr.co/edit/NfiVnQNes1p8PvXd1fCG?p=preview -
ARK over 6 yearscan you combine two variables eg. if(value1 && value2) to check if both of them are undefined ?
-
ARK over 6 yearscan you combine two variables eg. if(value1 && value2) to check if both of them are undefined ?
-
Ramazan Sağır over 6 years@AkshayrajKore yes you can
-
Alex over 6 yearsAnd 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 over 6 years@Alex if the value==0 returns false
-
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 over 6 yearsHow about checking for not null or undefined? Is
if ( x!= null)
equivalent toif (!(x != null))
? -
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 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 almost 6 yearsThis solution will not work if the tslint rule - "strict-boolean-expressions" is enabled.
-
justcode over 5 yearsM. Kamal if something = 0, your verification with !something will give you problems.
-
Ahmed Kamal over 5 years@arturios can you please give me an example!!
-
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 over 5 years@arturios But 0 is already a falsy value in JavaScript !! so what is the point here?
-
justcode over 5 yearsYes 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 over 5 yearsFor 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 undefinedsth
for the teststh !== null
-
Ahmed Kamal over 5 years@Al-un nope, see it in action here
-
paul cheung over 5 yearsso, if someValue is 'false'(with string type), then !!someValue is false(boolean type)?
-
avi.elkharrat over 5 yearsI guess you may say so.This technic is precisely used to avoid having this kind of confusion. I hope you like it!
-
paul cheung over 5 yearsbut what confused me is !!'false' equals true. Just because of this case, i can not use this technic.
-
avi.elkharrat over 5 years
!!'false'
is in deedtrue
because'false'
is a valid string -
paul cheung over 5 yearsso this technic can not cover this case, or is there a workaround solution?
-
Thomas Poignant about 5 yearsWhy this method are -2 ? Lodash is not good with type script ?
-
Jaider almost 5 yearsthe updated version is wrong. The first thing to check should be undefined... like:
if(typeof something !== 'undefined' && something !== null){...}
-
tkd_aj over 4 yearsThis 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 about 4 yearsIt will evaluate false if value us falsy, as simple as this.
-
carlosvini about 4 yearssomethingToCompare == (undefined || null). (undefined || null) resolves to null, so it's a loose comparison between somethingToCompare and null
-
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 about 4 years@ianstigator A boolean can be evaluated as
true
orfalse
only. If you have a boolean with anull
assignation or anundefined
value, in both cases the value will be evaluated asfalse
. -
Dmitry over 3 yearsOptional chaining and Nullish Coalescing are great but in case of a single
if
stmt likeif (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 over 3 yearsI 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 asa == b || a == c
, instead it will evaluateb || c
(in this case toc
sinceb
is falsy in your example) and then compare that againsta
. -
Totati over 3 yearsI wish they added this as an util function.
-
stonedauwg over 3 years@Fenton I think u meant to say "as falsy" instead of "as null"
-
hien over 3 yearsYes, for almost scenarios, we could we
Optional chaining
, e.g.if (foo?.bar?.baz)
typescriptlang.org/docs/handbook/release-notes/… -
Sindri Þór about 3 yearsWorks great here
-
Aleksei about 3 yearsFrom the function docs: deprecated since v4.0.0 - use
value === null || value === undefined
instead. -
Skrymsli almost 3 yearsIs there any practical difference between juggling and type coercion? Why do we need two terms?
-
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 almost 3 years@counterflow then you need to explicitly check for it:
if (typeof value == 'boolean')
-
Reactgular almost 3 yearsYou 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 almost 3 yearsNote 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 over 2 yearsI 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 over 2 years@Reactgular my test cases cover why that's not the solution.
-
Fenton over 2 years@spierala correct, it's just JavaScript.
-
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 isnull
orundefined
, then the original code will return the opposite of the correct answer. -
refaelio over 2 years@Aleksei that's ironic
-
SacredGeometry about 2 yearsDo you mean less concise?
-
blwinters about 2 yearsThis should be the accepted answer in 2022
-
vinsinraw about 2 yearsNullish Coalescing seems not supported in typescript 4.5.4. Is it deprecated?
-
vinsinraw about 2 yearsTried 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';