What does an exclamation mark before a variable mean in JavaScript

后端 未结 4 1470
说谎
说谎 2020-11-28 08:13

I\'m trying to learn JavaScript by going through some code in an application and I keep seeing !variable in if conditions. For example:

if (!va         


        
4条回答
  •  暖寄归人
    2020-11-28 09:01

    The selected answer already answers the question. One thing to add in this is that ! operator can be used in a rather interesting fashion.

    obj = {}
    if (!!obj) {console.log('works')} // !!obj = true
    obj = undefined
    if (!!obj) {console.log('does not work')} // !!obj = false
    

    So double !! will change any expression to a boolean value with no exceptions.

    This has a very peculiar use case in some cases.

    • Lets say there is a function that returns either true or false and nothing else. In that case one could just change return returnValue to return !!returnValue for extra caution (although not need in most of the cases)

    • Conversely, if a function only accepts true or false and nothing else, one could just call the function as functionA(!!parameter) instead of functionA(parameter), which again is not needed in most of the cases, but could ensure extra security

提交回复
热议问题