var javascriptIsCool = true;
alert( javascriptIsCool ); // returns "true", of course
alert( !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!var emptyString = ""; // Empty strings always evaluate as FALSE
alert( 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 = "";
You won't see any alert() message, because the statement evaluates as false in both cases.
if( emptyString )
alert( "Evaluates as TRUE! (Test # 1)" );
if( Boolean( emptyString ) ) // Notice the uppercase 'B'
alert( "Evaluates as TRUE! (Test # 2)" );
var emptyString = ""; // We know that it evaluates as false
alert( !!emptyString ); // Converts emptyString to boolean
var emptyString = ""; // We know that it evaluates as false
alert( Boolean( emptyString ) ); // Returns "false", as expected
Tip - here are a few automatic conversions JavaScript makes when evaluating expressions:
• NaN, zero, or negative numbers → FALSE
• Strings of length less than one → FALSE.
• null and undefined also evaluate as FALSE. // So it follows, that:
alert( ! 0 ); // ...should evaluate as true
alert( ! null ); // ...true