JavaScript Unary Negation Operator (Exclamation Mark)

The "!" exclamation point is part of JavaScript's logical operators, and is called the "unary negation operator", or more simply "logical NOT". It negates the expression that follows it: var javascriptIsCool = true;alert( javascriptIsCool ); // returns "true", of coursealert( !javascriptIsCool ); // returns "false" - try it → The exclamation mark doesn't have to be stuck to the variable or expression that follows it either - a space in between works as well, it's up to your personal coding preferences!

Behind-the-scenes, when the JavaScript interpreter encounters a logical negation operator, it tries to convert whatever follows into a boolean value ( TRUE / FALSE ). var emptyString = ""; // Empty strings always evaluate as FALSEalert( emptyString == true );Explanation: translated into spoken English, the second line in the snippet above basically asks to JavaScript "Is the emptyString variable considered 'true', when evaluated as a boolean?"

Tip: to force JavaScript to convert an object or variable to its boolean value, you can use the Boolean() constructor. But that conversion is automatically made inside an if() statement: var emptyString = "";if( emptyString ) alert( "Evaluates as TRUE! (Test # 1)" );if( Boolean( emptyString ) ) // Notice the uppercase 'B' alert( "Evaluates as TRUE! (Test # 2)" ); You won't see any alert() message, because the statement evaluates as false in both cases.

If you see two exclamation points back-to-back in a script, it has a special meaning. As you saw above, adding an exclamation mark in front of an expression tries to convert it to its boolean equivalent, but has the downside of negating it as well. So a quick (but potentially confusing) way of checking the boolean value of an expression is to use the negation operator twice in a row: the first time, it converts to opposite of boolean interpreted value, and the second time, it takes the actual value (the opposite of the opposite :) var emptyString = ""; // We know that it evaluates as falsealert( !!emptyString ); // Converts emptyString to boolean

To be nice with people who will have to read or maintain your code, explicitly comment the reasons for using two exclamation marks, or use a clearer approach, like the Boolean constructor: var emptyString = ""; // We know that it evaluates as falsealert( Boolean( emptyString ) ); // Returns "false", as expected