I saw some Javascript code which the CRM Developer Pacman was working on and it had a bizarre If statement which used a double exclamation mark!!
One exclamation mark means not but what does two exclamation marks mean Not Not?
Below is the code in question
var roleName = null; $.ajax({ type: "GET", async: false, contentType: "application/json; charset=utf-8", datatype: "json", url: odataSelect, beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); }, success: function (data, textStatus, XmlHttpRequest) { var result = data.d; if (!!result) { roleName = result.results[0].Name; } }, error: function (XmlHttpRequest, textStatus, errorThrown) { //alert('OData Select Failed: ' + odataSelect); } });
The code was doing an OData query and then checking the result with the if Statement
if (!!result) {
roleName = result.results[0].Name;
}
What does the !! exclamation do
It’s quite clever because the first exclamation mark converts the object into a boolean value, the second exclamation mark checks to see if the boolean is false.
In C# developer terms its like casting the object to a boolean and then doing an inverted check (e.g. if not false)
This two Stackoverflow articles discuss and explain the !! exclamation in more detail but this answer and the truth table helped me understand
''=='0'// false0==''// true0=='0'// truefalse=='false'// falsefalse=='0'// truefalse==undefined// falsefalse==null// falsenull==undefined// true" \t\r\n"==0// true
Using the table above my understand is the !! exclamation in the examples checks to see if the result object is not 0, undefined, null because all those values would be converted to a boolean type of false.
Here is another good discussion on the topic
What is the !! (not not) operator in JavaScript?
Whilst researching this topic I found the article below
Truthy and falsy in JavaScript
The article talks you understand how Javascript uses true, truthy, false and falsy in JavaScript
Filed under: Javascript