Let’s use a simple example to illustrate:
var o={ flag:true};
var test=!!o.flag;//Equivalent to var test=o.flag||false;
alert(test);
Due to Using the ! operator on null and undefined will produce a true result, so the purpose of using two exclamation marks is that if the value of the flag in o is explicitly set (not null/undefined/0""/etc.), the natural test It will take the same value as o.flag; if not set, test will default to false instead of null or undefined.
The classic example in jQuery is as follows: (jQuery 1.7.0.js: Line 748)
grep: function(elems, callback, inv) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i ) {
retVal = !! callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
}
When using the grep function, if the third parameter is given and is not null/undefined/0""/, then inv is true, otherwise it is false. The purpose of this is to ensure that the values of inv and retVal can only be taken from true/false, not other values, to facilitate subsequent judgments.