706

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?

MathMax
  • 571
  • 7
  • 22
David Liu
  • 16,374
  • 12
  • 37
  • 38
  • 23
    ```Since TypeScript is strongly-typed``` I couldn't find this in it's docs and I have doubts about it... – pawciobiel Aug 31 '15 at 14:01
  • 4
    Recommend to read up on the latest non-nullable types , this is Typescript 2 , but already in beta as of today. [Non-nullable types #7140] (https://github.com/Microsoft/TypeScript/pull/7140) – RyBolt Aug 05 '16 at 13:10
  • 3
    TypeScript has no dedicated functions to do anything. It's a typing system and a transpiler, not a library. –  Aug 09 '17 at 08:18
  • As you say it is bad to just check `if () {}` since that will also be true for `0`. – Tom el Safadi Aug 21 '20 at 09:18

28 Answers28

637

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"

Fenton
  • 241,084
  • 71
  • 387
  • 401
  • 113
    What is "juggling-check"? – kolobok Aug 01 '16 at 12:55
  • 34
    @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`. – Fenton Aug 01 '16 at 13:34
  • 25
    This is due to JS's 'type coercion'. – Astravagrant Jan 16 '17 at 13:19
  • Except if x is 0 (and that's a valid value), it will pass your undefined/null test. – Jon Gunter Jun 22 '17 at 16:25
  • 3
    @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`. – Fenton Aug 09 '17 at 18:47
  • Is if(!x) equal to if(x == null)? – developer Nov 03 '17 at 15:03
  • 2
    @developer - not quite, as `if (!x)` would treat (for example) the number `0` and the string `''` as null, whereas `if (x == null)` would not. – Fenton Nov 04 '17 at 09:11
  • How about checking for not null or undefined? Is `if ( x!= null)` equivalent to `if (!(x != null))`? – Mark Meuer Mar 13 '18 at 16:33
  • 1
    @Fenton I think u meant to say "as falsy" instead of "as null" – stonedauwg Dec 04 '20 at 14:56
  • Is there any practical difference between juggling and type coercion? Why do we need two terms? – Skrymsli Aug 17 '21 at 18:10
  • @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). – Fenton Aug 19 '21 at 08:30
  • 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. – Reactgular Sep 22 '21 at 12:43
  • 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. – spierala Oct 18 '21 at 07:25
  • @Reactgular my test cases cover why that's not the solution. – Fenton Oct 21 '21 at 15:31
  • @spierala correct, it's just JavaScript. – Fenton Oct 21 '21 at 15:31
453
if( value ) {
}

will evaluate to true if value is not:

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

typescript includes javascript rules.

kingdaro
  • 11,528
  • 3
  • 34
  • 38
Ramazan Sağır
  • 4,887
  • 1
  • 14
  • 15
  • 48
    What if value is of boolean type? – counterflow Oct 06 '17 at 22:56
  • 2
    can you combine two variables eg. if(value1 && value2) to check if both of them are undefined ? – ARK Nov 17 '17 at 16:52
  • @AkshayrajKore yes you can – Ramazan Sağır Nov 22 '17 at 14:34
  • 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 ? – Alex Feb 27 '18 at 09:55
  • @Alex if the value==0 returns false – Ramazan Sağır Feb 27 '18 at 10:11
  • 14
    @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) – Alex Feb 27 '18 at 10:31
  • @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 Jun 02 '18 at 04:43
  • @RamazanSağır I found the reason it's because of double quote surrounding undefined keyword. Otherwise if (undefined) evaluated to false; – Yohan Hirimuthugoda Jun 02 '18 at 04:50
  • 8
    This solution will not work if the tslint rule - "strict-boolean-expressions" is enabled. – ip_x Sep 24 '18 at 11:43
  • 1
    It will evaluate false if value us falsy, as simple as this. – Ayfri Apr 18 '20 at 04:11
  • @counterflow then you need to explicitly check for it: `if (typeof value == 'boolean')` – Kamafeather Sep 20 '21 at 19:48
173

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

Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52
  • 18
    This should be the accepted answer now. Typescript 3.7 also supports "Nullish Coalescing". var foo = possibleUndefinedOrNull ?? fallbackValueIfFirstValueIsUndefinedOrNull; Here is the documentation: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html – tkd_aj Nov 25 '19 at 22:12
  • 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 https://stackoverflow.com/a/28984306/407986 – Dmitry Oct 28 '20 at 05:12
  • Yes, for almost scenarios, we could we `Optional chaining` , e.g. `if (foo?.bar?.baz)` https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html – hien Jan 08 '21 at 06:25
  • Nullish Coalescing seems not supported in typescript 4.5.4. Is it deprecated? – vinsinraw Jun 20 '22 at 11:56
  • 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'; – vinsinraw Jun 20 '22 at 12:03
  • NOTE: `if (foo?.bar?.baz) { // ... }` is not a strict null|undefined check as it will be false if `baz` itself is fasley (zero, false, empty dict, empty list, etc) – Nicholas Franceschina Nov 02 '22 at 21:37
90

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

basarat
  • 261,912
  • 58
  • 460
  • 511
  • 4
    I like doing two equals `myVar == null`. Just another option. – David Sherret Mar 11 '15 at 02:09
  • 44
    `== 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. – C Snover Mar 11 '15 at 03:04
44

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
Juangui Jordán
  • 6,091
  • 2
  • 35
  • 31
  • 1
    Why would you use the TypeScript playground for this? Nothing here has anything to do with TypeScript. –  Aug 10 '17 at 04:37
  • 13
    Because the question was related to Typescript, I was trying to test different proposed solutions against the Typescript transpiler. – Juangui Jordán Aug 11 '17 at 07:51
  • 7
    The TS transpiler would not transform any of this code at all. –  Aug 11 '17 at 08:32
42

You may want to try

if(!!someValue)

with !!.

Explanation

The first ! will turn your expression into a boolean value.

Then !someValue is true if someValue is falsy and false if someValue is truthy. This might be confusing.

By adding another !, the expression is now true if someValue is truthy and false if someValue is falsy, which is much easier to manage.

Discussion

Now, why do I bother myself with if (!!someValue) when something like if (someValue) would have give me the same result?

Because !!someValue is precisely a boolean expression, whereas someValue could be absolutely anything. This kind of expression will now alow to write functions (and God we need those) like:

isSomeValueDefined(): boolean {
  return !!someValue
}

instead of:

isSomeValueDefined(): boolean {
  if(someValue) {
    return true
  }
  return false
}

I hope it helps.

avi.elkharrat
  • 6,100
  • 6
  • 41
  • 47
37

For Typescript 2.x.x you should do it in a following way(using type guard):

tl;dr

function isDefined<T>(value: T | undefined | null): value is T {
  return <T>value !== undefined && <T>value !== null;
}

Why?

In this way isDefined() will respect variable's type and the following code would know take this check in account.

Example 1 - basic check:

function getFoo(foo: string): void { 
  //
}

function getBar(bar: string| undefined) {   
  getFoo(bar); //ERROR: "bar" can be undefined
  if (isDefined(bar)) {
    getFoo(bar); // Ok now, typescript knows that "bar' is defined
  }
}

Example 2 - types respect:

function getFoo(foo: string): void { 
  //
}

function getBar(bar: number | undefined) {
  getFoo(bar); // ERROR: "number | undefined" is not assignable to "string"
  if (isDefined(bar)) {
    getFoo(bar); // ERROR: "number" is not assignable to "string", but it's ok - we know it's number
  }
}
Maxim Pyshko
  • 551
  • 4
  • 14
S Panfilov
  • 16,641
  • 17
  • 74
  • 96
  • 2
    I wish they added this as an util function. – Totati Nov 12 '20 at 21:48
  • 3
    Note that the check for nullish should be defined like this: ```function isNullish(value: T | undefined | null): value is undefined | null { return value === undefined || value === null; }``` – Kfir Dadosh Sep 23 '21 at 13:42
  • 1
    @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. – Steven Obua Dec 29 '21 at 08:10
  • 2
    This should be the accepted answer in 2022 – blwinters Apr 06 '22 at 21:31
35

SIMPLE ANSWER

Although Typescript is a strongly typed language, it has the same problems with pointers and variables initialization inherited from Javascript.
Javascript doesn't check whether a variable exists in the context, the so common undefined status.

to evaluate if value ISN'T null,undefined,0,false,"", or NaN:

if ( value )
or
if ( !!value )

for negative conditional, check if the value is null,undefined,0,false,"",or NaN:

if ( !value )

to test if is null or undefined:

if ( value == null )

to test only null:

if ( value === null )

to test only undefined:

if ( value === undefined )

MORE DETAILED ANSWER

1- It will evaluate to true if value is not: null, undefined, NaN, empty string '', 0, false
If the value is null,undefined,NaN,empty string,0, or false, will go to the else condition.

if ( value ) {
  console.log('value is something different from 0, "", false, NaN, null, undefined');
} else {
  console.log('value is 0, "", false, NaN, null or undefined');
}
if ( !!value ) {
  console.log('value is something different from 0, "", false, NaN, null, undefined');
} else {
  console.log('value is 0, "", false, NaN, null or undefined');
}

2- If you want a negative condition, then you'll need to use:

if ( !value ) {
  console.log('value is 0, "", false, NaN, null or undefined');
} else {
  console.log('value is something different from 0, "", false, NaN, null, undefined');
}

3- It will evaluate if value is null or undefined

if ( value == null ) {
  console.log('is null or undefined');
} else {
  console.log('it isnt null neither undefined');
}

4- Using a test with boolean values doesn't work.
It will NOT evaluate to true neither to false if value is null, undefined, 0, empty string, NaN
Both conditions will always go to the else condition.
With the exception if value is a boolean variable.

if ( value==true ) {
} else { 
}
if ( value==false ) {
} else { 
}
danilo
  • 7,680
  • 7
  • 43
  • 46
31

I think this answer needs an update, check the edit history for the old answer.

Basically, you have three deferent cases null, undefined, and undeclared, see the snippet below.

// bad-file.ts
console.log(message)

You'll get an error says that variable message is undefined (aka undeclared), of course, the Typescript compiler shouldn't let you do that but REALLY nothing can prevent you.

// evil-file.ts
// @ts-gnore
console.log(message)

The compiler will be happy to just compile the code above. So, if you're sure that all variables are declared you can simply do that

if ( message != null ) {
    // do something with the message
}

the code above will check for null and undefined, BUT in case the message variable may be undeclared (for safety), you may consider the following code

if ( typeof(message) !== 'undefined' && message !== null ) {
    // message variable is more than safe to be used.
}

Note: the order here typeof(message) !== 'undefined' && message !== null is very important you have to check for the undefined state first atherwise it will be just the same as message != null, thanks @Jaider.

Ahmed Kamal
  • 2,660
  • 3
  • 21
  • 36
  • 4
    M. Kamal if something = 0, your verification with !something will give you problems. – justcode Nov 21 '18 at 10:35
  • 1
    @arturios can you please give me an example!! – Ahmed Kamal Nov 21 '18 at 13:24
  • @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") } – justcode Nov 21 '18 at 15:02
  • 2
    @arturios But 0 is already a falsy value in JavaScript !! so what is the point here? – Ahmed Kamal Nov 21 '18 at 17:01
  • Yes i understand but the question refers only to undefined and null, but now i look that you put the comment of false also. – justcode Nov 21 '18 at 17:46
  • 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` – Al-un Jan 17 '19 at 17:10
  • 1
    @Al-un nope, see it in action [here](http://www.typescriptlang.org/play/#src=%2F%2F%20it's%20undefined.%0D%0Aconst%20something%20%3D%20undefined%0D%0A%0D%0Aif%20(something%20!%3D%3D%20null%20%26%26%20typeof%20something%20!%3D%3D%20'undefined')%20%7B%0D%0A%20%20%2F%2F%20your%20logic%20here...%0D%0A%7D%20else%20%7B%0D%0A%20%20%20%20console.log('NOPE%2C%20no%20errors!')%0D%0A%7D) – Ahmed Kamal Jan 17 '19 at 23:45
  • 1
    the updated version is wrong. The first thing to check should be undefined... like: `if(typeof something !== 'undefined' && something !== null){...}` – Jaider Jul 10 '19 at 17:17
15
if(data){}

it's mean !data

  • null
  • undefined
  • false
  • ....
artemitSoft
  • 286
  • 5
  • 17
8

UPDATE (Sept 4, 2020)

You can now use the ?? operator to validate null and undefined "values" and set a default value. For example:

const foo = null;
const bar = foo ?? 'exampleValue';
console.log(bar); // This will print 'exampleValue' due to the value condition of the foo constant, in this case, a null value

As a verbose way, if you want to compare null and undefined values ONLY, use the following example code for reference:

const incomingValue : string = undefined;
const somethingToCompare : string = incomingValue; // If the line above is not declared, TypeScript will return an excepion

if (somethingToCompare == (undefined || null)) {
  console.log(`Incoming value is: ${somethingToCompare}`);
}

If incomingValue is not declared, TypeScript should return an exception. If this is declared but not defined, the console.log() will return "Incoming value is: undefined". Note we are not using the strict equals operator.

The "correct" way (check the other answers for details), if the incomingValue is not a boolean type, just evaluate if its value is true, this will be evaluated according to the constant/variable type. A true string have to be defined explicitly as string using the = '' assignation. If not, it will be evaluated as false. Let's check this case using the same context:

const incomingValue : string = undefined;
const somethingToCompare0 : string = 'Trumpet';
const somethingToCompare1 : string = incomingValue;

if (somethingToCompare0) {
  console.log(`somethingToCompare0 is: ${somethingToCompare0}`); // Will return "somethingToCompare0 is: Trumpet"
}

// Now, we will evaluate the second constant
if (somethingToCompare1) {
  console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is defined
} else {
  console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is undefined. Will return "somethingToCompare1 is: undefined"
}
KBeDev
  • 387
  • 5
  • 9
  • 3
    somethingToCompare == (undefined || null). (undefined || null) resolves to null, so it's a loose comparison between somethingToCompare and null – carlosvini Apr 23 '20 at 19:38
  • @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 Apr 23 '20 at 20:02
  • 1
    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`. – CherryDT Nov 07 '20 at 20:33
7

If you want to pass tslint without setting strict-boolean-expressions to allow-null-union or allow-undefined-union, you need to use isNullOrUndefined from node's util module or roll your own:

// tslint:disable:no-null-keyword
export const isNullOrUndefined =
  <T>(obj: T | null | undefined): obj is null | undefined => {
    return typeof obj === "undefined" || obj === null;
  };
// tslint:enable:no-null-keyword

Not exactly syntactic sugar but useful when your tslint rules are strict.

Graeme Wicksted
  • 1,770
  • 1
  • 18
  • 21
6

If you are using TypeScript, it is a better approach to let the compiler check for nulls and undefineds (or the possibility thereof), rather than checking for them at run-time. (If you do want to check at run-time, then as many answers indicate, just use value == null).

Use the compile option strictNullChecks to tell the compiler to choke on possible null or undefined values. If you set this option, and then there is a situation where you do want to allow null and undefined, you can define the type as Type | null | undefined.

3

The simplest way is to use:

import { isNullOrUndefined } from 'util';

and than:

if (!isNullOrUndefined(foo))

Ruthi
  • 312
  • 1
  • 4
  • 12
2

We use a helper hasValue that both checks for nulls/undefined and ensures via TypeScript that unnecessary checks are not performed. (The latter is similar to how TS would complain about if ("a" === undefined), since it is always false).

Using this consistently is always safe, unlike !val which matches empty strings, zero, etc. It also avoid the use of fuzzy == matching which is almost always a bad practice - no need to introduce an exception.



type NullPart<T> = T & (null | undefined);

// Ensures unnecessary checks aren't performed - only a valid call if 
// value could be nullable *and* could be non-nullable
type MustBeAmbiguouslyNullable<T> = NullPart<T> extends never
  ? never
  : NonNullable<T> extends never
  ? never
  : T;

export function hasValue<T>(
  value: MustBeAmbiguouslyNullable<T>,
): value is NonNullable<MustBeAmbiguouslyNullable<T>> {
  return (value as unknown) !== undefined && (value as unknown) !== null;
}

export function hasValueFn<T, A>(
  value: MustBeAmbiguouslyNullable<T>,
  thenFn: (value: NonNullable<T>) => A,
): A | undefined {
  // Undefined matches .? syntax result
  return hasValue(value) ? thenFn(value) : undefined;
}


Freewalker
  • 6,329
  • 4
  • 51
  • 70
2

May be to late! but you can use ?? operator in typescript. see https://mariusschulz.com/blog/nullish-coalescing-the-operator-in-typescript

Ali Qamsari
  • 93
  • 1
  • 10
2

It can be done like this:

 // value is the value which you want to check
 [undefined, null].includes(value)
H S W
  • 6,310
  • 4
  • 25
  • 36
1

Late to join this thread but I find this JavaScript hack very handy in checking whether a value is undefined

 if(typeof(something) === 'undefined'){
   // Yes this is undefined
 }
Shahid Manzoor Bhat
  • 1,307
  • 1
  • 13
  • 32
1

You can do this easily with a ternary operator and the new nullish coalesce operator.

First: check to see if it is true using the ternary. If so return false so the if statement does not run.

Second: because you now know the value is falsey, you can use the nullish coalesce operator to return true if it is nullish. Since it will return itself for any other value, if it is not nullish it will fail the if statement correctly.

let x = true;
console.log("starting tests")

if (x?false:x ?? true){
  console.log(x,"is nullish")
}

x = false
if (x?false:x ?? true){
  console.log(x,"is nullish")
}

x = 0;
if (x?false:x ?? true){
  console.log(x,"is nullish")
}

x=1;
if (x?false:x ?? true){
  console.log(x,"is nullish")
}

x="";
if (x?false:x ?? true){
  console.log(x,"is nullish")
}

x="hello world";
if (x?false:x ?? true){
  console.log(x,"is nullish")
}

x=null;
if (x?false:x ?? true){
  console.log(x,"is nullish")
}

x=undefined;
if (x?false:x ?? true){
  console.log(x,"is nullish")
}
Daniel
  • 1,392
  • 1
  • 5
  • 16
0

you can use

if(x === undefined)
Julian
  • 33,915
  • 22
  • 119
  • 174
0

All,

The answer with the most votes, does not really work if you are working with an object. In that case, if a property is not present, the check will not work. And that was the issue in our case: see this sample:

var x =
{ name: "Homer", LastName: "Simpson" };

var y =
{ name: "Marge"} ;

var z =
{ name: "Bart" , LastName: undefined} ;

var a =
{ name: "Lisa" , LastName: ""} ;

var hasLastNameX = x.LastName != null;
var hasLastNameY = y.LastName != null;
var hasLastNameZ = z.LastName != null;
var hasLastNameA = a.LastName != null;



alert (hasLastNameX + ' ' + hasLastNameY + ' ' + hasLastNameZ + ' ' + hasLastNameA);

var hasLastNameXX = x.LastName !== null;
var hasLastNameYY = y.LastName !== null;
var hasLastNameZZ = z.LastName !== null;
var hasLastNameAA = a.LastName !== null;

alert (hasLastNameXX + ' ' + hasLastNameYY + ' ' + hasLastNameZZ + ' ' + hasLastNameAA);

Outcome:

true , false, false , true (in case of !=)
true , true, true, true (in case of !==) => so in this sample not the correct answer

plunkr link: https://plnkr.co/edit/BJpVHD95FhKlpHp1skUE

Ben Croughs
  • 2,566
  • 1
  • 20
  • 30
  • This is not good test. None of those values are *strictly* `null`. Try this: https://plnkr.co/edit/NfiVnQNes1p8PvXd1fCG?p=preview – simonhamp Nov 09 '17 at 12:46
0

Since TypeScript is a typed superset of ES6 JavaScript. And lodash are a library of javascript.

Using lodash to checks if value is null or undefined can be done using _.isNil().

_.isNil(value)

Arguments

value (*): The value to check.

Returns

(boolean): Returns true if value is nullish, else false.

Example

_.isNil(null);
// => true

_.isNil(void 0);
// => true

_.isNil(NaN);
// => false

Link

Lodash Docs

7e2e63de
  • 37
  • 3
0

A faster and shorter notation for null checks can be:

value == null ? "UNDEFINED" : value

This line is equivalent to:

if(value == null) {
       console.log("UNDEFINED")
} else {
    console.log(value)
}

Especially when you have a lot of null check it is a nice short notation.

SparklyUnicorn
  • 1
  • 2
  • 5
  • 18
0

I had this issue and some of the answer work just fine for JS but not for TS here is the reason.

//JS
let couldBeNullOrUndefined;
if(couldBeNullOrUndefined == null) {
  console.log('null OR undefined', couldBeNullOrUndefined);
} else {
  console.log('Has some value', couldBeNullOrUndefined);
}

That is all good as JS has no Types

//TS
let couldBeNullOrUndefined?: string | null; // THIS NEEDS TO BE TYPED AS undefined || null || Type(string)

if(couldBeNullOrUndefined === null) { // TS should always use strict-check
  console.log('null OR undefined', couldBeNullOrUndefined);
} else {
  console.log('Has some value', couldBeNullOrUndefined);
}

In TS if the variable wasn't defined with null when you try to check for that null the tslint | compiler will complain.

//tslint.json
...
"triple-equals":[true],
...
 let couldBeNullOrUndefined?: string; // to fix it add | null

 Types of property 'couldBeNullOrUndefined' are incompatible.
      Type 'string | null' is not assignable to type 'string | undefined'.
        Type 'null' is not assignable to type 'string | undefined'.
T04435
  • 12,507
  • 5
  • 54
  • 54
0

Usually I do the juggling-check as Fenton already discussed. To make it more readable, you can use isNil from ramda.

import * as isNil from 'ramda/src/isNil';

totalAmount = isNil(totalAmount ) ? 0 : totalAmount ;
Neo
  • 233
  • 2
  • 3
0

careful if you're using local storage, you can end up with the string undefined rather than the value undefined:

localStorage.setItem('mykey',JSON.stringify(undefined));
localStorage.getItem('mykey') === "undefined"
true

People may find this useful: https://github.com/angular/components/blob/master/src/cdk/coercion/boolean-property.spec.ts

/**
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

/** Coerces a data-bound value (typically a string) to a boolean. */
export function coerceBooleanProperty(value: any): boolean {
  return value != null && `${value}` !== 'false';
}

import {coerceBooleanProperty} from './boolean-property';

describe('coerceBooleanProperty', () => {

  it('should coerce undefined to false', () => {
    expect(coerceBooleanProperty(undefined)).toBe(false);
  });

  it('should coerce null to false', () => {
    expect(coerceBooleanProperty(null)).toBe(false);
  });

  it('should coerce the empty string to true', () => {
    expect(coerceBooleanProperty('')).toBe(true);
  });

  it('should coerce zero to true', () => {
    expect(coerceBooleanProperty(0)).toBe(true);
  });

  it('should coerce the string "false" to false', () => {
    expect(coerceBooleanProperty('false')).toBe(false);
  });

  it('should coerce the boolean false to false', () => {
    expect(coerceBooleanProperty(false)).toBe(false);
  });

  it('should coerce the boolean true to true', () => {
    expect(coerceBooleanProperty(true)).toBe(true);
  });

  it('should coerce the string "true" to true', () => {
    expect(coerceBooleanProperty('true')).toBe(true);
  });

  it('should coerce an arbitrary string to true', () => {
    expect(coerceBooleanProperty('pink')).toBe(true);
  });

  it('should coerce an object to true', () => {
    expect(coerceBooleanProperty({})).toBe(true);
  });

  it('should coerce an array to true', () => {
    expect(coerceBooleanProperty([])).toBe(true);
  });
});
Rusty Rob
  • 16,489
  • 8
  • 100
  • 116
-1

You could use:

if (!!variable) {}

it equals writting

it (variable != null && variable != undefined) {}
  • 3
    This would omit any value that *could* be valid that resolves to false when double-negated, such as 0 or an empty string. – mwieczorek Oct 27 '22 at 09:20
-7

I always write it like this:

var foo:string;

if(!foo){
   foo="something";    
}

This will work fine and I think it's very readable.

Rusty Rob
  • 16,489
  • 8
  • 100
  • 116
AlexB
  • 687
  • 2
  • 7
  • 15
  • 26
    Wouldn't work for numbers because `0` also passes the `!foo` test. – hasen May 18 '16 at 17:58
  • 10
    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 */ }` – Gingi May 27 '16 at 18:00
  • 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? – Drenai Aug 07 '16 at 19:10