Double Exlamation

Apply double exclamation to a variable to ensure it is boolean.

jQuery uses the double exclamation idiom about 20 times throughout its code base.



Overview


The Double exclamation idiom converts an expression or or value that is truthy or falsy to a true boolean value. This is discussed in the Essentials section. jQuery uses it in several places throughout its code base. The grep method uses it twice:

grep: function (elems, callback, inv) {
    var retVal,
        ret = [],
        i = 0,
        length = elems.length;
    inv = !!inv;

    // Go through the array, only saving the items
    // that pass the validator function
    for (; i < length; i++) {
        retVal = !!callback(elems[i], i);
        if (inv !== retVal) {
            ret.push(elems[i]);
        }
    }

    return ret;
}

In incoming inv argument is converted to a Boolean and the return value of the callback invocation also.