DEV Community

Musab
Musab

Posted on • Updated on

TypeScript and the NOT (!) operator in the context of an if statement

A quick write up on better understanding of the ! (NOT) operator in JavaScript / TypeScript.

I had to find a way to stop a null value from progressing to the next statement in a TypeScript file.

In order to do this I used the ! operator as follows:

const name = await doingsomethingasync

\\"name" can be a string, number or null
\\The if statement below catches the null value keeping TypeScript happy!

if (!name){
    throw new Error("name is null") 
} 
Enter fullscreen mode Exit fullscreen mode

So what's happening here exactly?

Placing a ! infront of a value does two things

  1. The value gets coerced to a boolean
  2. It then gets inverted

So, if name is a string, as a coerced boolean it evaluates to true (remember JavaScript truthy and falsy), inverting it means the statement !name will evaluate to false.

Likewise, if name is a number, it's coerced to a boolean which evaluates to true, then inverts to false.

However, if name is null, it's coerced to a boolean evaluation of false (remember null is falsy value), when inverted it will evaluate to true.

This approach ensures the if statement targeting the null condition will only execute when name is null, permitting a continuation of the program otherwise.

All in all, ! is thoroughly useful tool to have in the toolbox.

Musab Hussain Banner | Musab Hussain, a software developer, writer, lifelong learner and solopreneur

Top comments (0)