double exclamation on a return value in javascript

This question already has an answer here:

  • What is the !! (not not) operator in JavaScript? 31 answers

  • The ! operator negates, and the secondary ! negates the result of the inital negation. This basically typecasts whatever is on the right hand side into a boolean ( true or false ).

    !false // true
    !!false // false
    

    So if the method is defined then the function which is truthy, will be typecasted into true .

    document.createElement('video').canPlayType
    

    So the above returns a function. We don't want a function, we want an explicit boolean, so we negative it twice and since function is not falsy ( 0, null, false, empty string, NaN ) then it returns true for browsers which support this method.

    !!document.createElement('video').canPlayType // true
    

    If the method is not supported, the browser will return undefined . !undefined is true, and !true is false, so !!document.createElement('video').LOL will return false


    The double exclamation is a JavaScript trick to return true/false regardless of input. In your example, if a browser does not support the video tag, it will return undefined. !undefined is true. So !!undefined is false. If the browser does support video, it will return true. !!true is also true. This saves you from having to handle the case of undefined.

    链接地址: http://www.djcxy.com/p/12648.html

    上一篇: javascript:什么是NOT NOT? (!!运营商)

    下一篇: 在javascript中返回值的双重感叹号