What’s the double exclamation sign for in JavaScript?
If you have ever noticed a double exclamation mark (!!) in someone’s JavaScript code you may be curious what it’s for and what it does. It’s really simple: it’s short way to cast a variable to be a Boolean (true or false) value. Let me explain.
Using a double exclamation point will instantly identify you as an over-excited internet poster under-familiar with the colloquial usage of English. (unless you’re writing in JavaScript, in which case it’s perfectly ok). The double exclamation point, or double bang, converts a truthy or falsy value to “true” or “false”. In other words, it operates exactly like Boolean(value) would.
The following values are considered by JavaScript to be falseys:
- Empty string:
""
- 0
- null
- undefined
- NaN
The following values are considered by JavaScript to be truthys:
- Object:
{}
- Array:
[]
- Not empty string:
"anything"
- Number other than zero:
3.14
- Date:
new Date();
The JavaScript engine that is executing your code will attempt to convert (or coerce) a value to a boolean when necessary, such as when evaluated in an if-statement.
JavaScript is not a static language, rather it is a dynamic language. That means that a variable can reference or hold a value of any type, and further, that type can be changed at any point. Whether you prefer a static or dynamic language is for you to decide.
But, we can certainly have a notion of a type in JavaScript. Here is a quick list of the various data types in JavaScript:
- Boolean
- String
- Number
- Object
Coerce object to boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true. A boolean data type is the simplest of all data types as it is a simple bit value: 0 (false) or 1 (true).
So !! is not an operator, it’s just the ! operator twice.
Let me explain with best example to detect IE version
let isIE8 = false;
isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);
console.log(isIE8); // returns true or false
If you use below code
console.log(navigator.userAgent.match(/MSIE 8.0/)); // returns either an Array or null
Instead if you use !! result will be different
console.log(!!navigator.userAgent.match(/MSIE 8.0/)); // returns either true or false
Thank you for reading!