JavaScript: Using Double Exclamation Marks !!

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:

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
}

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:

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

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.

Published by

Umar Ashfaq

Umar Ashfaq is a full-stack web developer. His core strength is building neat UIs with JavaScript on web but he also enjoys server side Java, NodeJS and Objective C. Follow him on twitter @umarashfaq87

One thought on “JavaScript: Using Double Exclamation Marks !!”

Leave a Reply

Your email address will not be published. Required fields are marked *