0

Possible Duplicate:
What is the !! (not not) operator in JavaScript?

Jquery Library souce code of $.grep.....

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 this example above is jquery grep on souce code of jquery library. Why he make inv as default is undefined and he changed to boolean and same thing retVal store the !!callback and change to the boolean. The issue is how if statement Works...?? Can give me some more details explanation..!! Thanks.

        retVal = !!callback( elems[ i ], i );
        if ( inv !== retVal ) {
            ret.push( elems[ i ] );
        }
Community
  • 1
  • 1
Iam_Signal
  • 331
  • 1
  • 4
  • 11
  • For !!, check this : http://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript and for !== Check these : http://www.c-point.com/javascript_tutorial/jsgrpComparison.htm and http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use – TJ- Oct 05 '12 at 12:42

1 Answers1

1

! is a unary operator that coerces the operand to a boolean and then returns the opposite. put two of them together (!!) and you get an operand coerced to a boolean and double negated - it's boolean representation. most people prefer Boolean(val) to !!val since it's much easier to understand.

// this calls "callback" and converts the return value to a boolean
retVal = !!callback( elems[ i ], i );
// if the converted return value is not identical to "inv" then... 
if ( inv !== retVal ) {
    // elems[i] is pushed on to the top of the array "ret"
    ret.push( elems[ i ] );
}

Note that the condition inv !== retVal could also be written inv != retVal since we know both inv and retVal are boolean types, but it is a good habit to always use identity operators even when a comparison operator would do.

jbabey
  • 45,965
  • 12
  • 71
  • 94