Exclamation Mark is not just “NOT” or “NOT NOT”

Use cases of exclamation mark in JavaScript and TypeScript

Photo by Vincent van Zalinge on Unsplash

We all know “!” as one of the logical operators in JavaScript to negate expression comes after it. For example:

!true === false 

Soon after, you might start to use NOT NOT operator which is just turn any expression into true or false based on if this value is truthy or falsy.

!!true === true

That should be enough, but in rare cases, you also see something like below, where “!” is placed in front of a function.

!function randomFunction(){}

What does this mean? Well if we look at the second half after the “!”, it’s just a function declaration: function randomFunction(){}

Now, adding the exclamation mark: !function randomFunction(){} will turn the function declaration into a function expression. In this way, it can be immediately invoked without wrapping it in parentheses like you normally do with immediately invoked function expression:(function randomFunction(){})()

So now you just need to do this:!function randomFunction() {}()

You can achieve the same conversion by using any of +,-,~,void operators.

You may ask: why would anyone ever want to do this?

Well, comparing the two below, the “!” saves a byte.

(function randomFunction(){})();
!function randomFunction(){}()

This pattern can appear in minification or uglification scripts, since you want to save every single byte.

The last bit is about TypeScript, but since it’s always used in conjunction with JavaScript, it’s good to mention it together.

So similar but not same, you can place “!” after an expression in TypeScript — the non-null assertion operator. It basically tells TypeScript that me as person who writes the code, am very confident that the operand will not be null or undefined during runtime.

(Obviously, only needed when --strictNullChecks is set to true)

So previously if I have a variable that can be a string array or null, and I try to access its first item by index 0 after I assign a string array to it, I will get error since from TypeScript perspective, it can also be null. But after adding the non-null assertion, this error is suppressed.

let s: string[]|null
s= ["notnullstring"]

Still, be cautious when you use it and only use it when necessary, otherwise you might run into errors that could have been avoided.

Happy learning!

Hi :)