-3

I don't understand this line as well

data: !!data && _.mapObject(data, ... 

What is the signification of "!!" In the following JS code?

$.ajax({
  type: "POST",
  url: url,
  dataType: "json",
  async: true,
  data:
    !!data &&
    _.mapObject(data, function(value) {
      return $.toJSON(value);
    }),
  statusCode: {
    500: function() {},
  },
  success: function(response) {
    if (_.isUndefined(response.isDocument)) {
      response.isDocument = that._currentSearch.type == "document";
    }

    if (response && response.searchResult) {
      $(response.searchResult.hits).each(function(i, item) {
        item.uniqueHitId = SearchModel.generateUniqueHitId();
        searchModel._cacheResult[item.uniqueHitId] = item;
      });

      successHandler(response, that.isFacetListFound, adaptHighlights, filters);
    } else {
      errorHandler("No result found", response.Error);
    }
  },
  error: errorHandler,
});

Normally, !! casts an object to a true value if this object is defined, but in my case, the content of data after this line is :

{
message: "data is not defined"
stack: "ReferenceError: data is not defined"}

Please see this screenshot from a debug result of the execution: enter image description here

1 Answers1

0

!! AKA doble not operator is used to make evidence that the value is a boolean or it will be casted as a boolean

One of the benefits of using the !! is to convey that your design decision was to only return a true or false value. When you or someone else looks at that code and a !! is encountered, the only possible return values are true or false. It is a matter of contention if readability is improved with the use of this logical tool.

The most common criticism of using !! is its seemingly added complexity that can be simplified with slightly more code that may have more flexibility. Another criticism relates to zero being a falsy value, so a lot of use cases related to numbers come with extra concerns.

Ref: https://medium.com/@edplatomail/js-double-bang-or-the-not-operator-part-40e55d089bf0

The && operator evaluate the argument precedes it (!!data) as a boolean and if it is true it will return the argument following the operator (_.mapObject(data, ...), otherwise it will return just false

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43