JavaScript: Using Double Exclamation Marks !!

Umar Ashfaq
Eastros
Published in
1 min readSep 9, 2012

I have found JavaScript to be a super intuitive language: you learn the basics well, rest of the things will crawl up to your mind themselves. Recently I had to write a function that would tell me if a string is null or empty. Of course you can directly use the string reference to test if it contains anything:

[sourcecode language=”javascript”]
if ( my_str ) {
// will execute if my_str points to a non-empty string
} else {
// will execute if my_str is null, undefined, false, 0 or points to an empty string
}
[/sourcecode]
But what if, for some reason, you need to create a variable is_null_or_empty and fill it with either true or false, depending upon the value of my_str. Double exclamation marks can help here:
[sourcecode language=”javascript”]
var isNullOrEmpty = function( str ) {
return !!str;
},
my_str = ‘Hello World!’,
is_null_or_empty = isNullOrEmpty( my_str );
alert( is_null_or_empty ); // will show true
[/sourcecode]
So as we know, if we pass a reference to a non-empty string to a boolean expression (such as the one in an if condition), it is treated as true. Adding a single exclamation mark before it would return false and another exclamation mark would return true. Hence, with a double exclamation mark, we can return boolean equivalent of a variable.

--

--