Friday, January 20, 2012

the double exclamation mark operator in JavaScript

Addendum 9/17/2013: Please see this for a better explanation as what follows is goofy.

getSelectedIds: function (backingStore) {

   var selectedIds = backingStore.find('option:selected').map(function () {

      return $(this).val();

   });

   return !!selectedIds ? selectedIds : [];

}

   

The second to last line above uses the double exclamation mark operator which fishes for not zero, not false, and not undefined in a variable's shape and allows one to do the sort of one line if/then operations that one associates with ?: in C#. This line empowers: If selectedIds is not zero, not false, and not undefined, then return selected Ids, otherwise return a new range in JavaScript that is empty.

2 comments:

  1. Note that:
    return selectedIds ? selectedIds : [];
    ...would result in the exact same results. In your example the !! (which actually isn't an operator in itself, but *two* operators) Is a double negative. The first "!" converts selectedIds into a Boolean and inverts it. The second "!" then inverts that inverted value, giving you the expected Boolean. JavaScript knows that you are treating selectedIds as a boolean already, so there is no functional reason for the "!!" that I know of, it merely shows intent to anyone reading your code. As such, this isn't to say you shouldn't use "!!", but I felt it required some clarification.

    ReplyDelete
  2. Thanks for your comment. I did some searching just now upon you leaving it and what I've Googled seems to reinforce what you say. It makes sense. Um, I sense another blog posting about this in the immediacy. Thanks again.

    ReplyDelete