What does “!” operator mean in javascript when it is used with a non-boolean variable?

后端 未结 5 447
小鲜肉
小鲜肉 2020-12-03 10:53

While reading through javascript codes I\'ve been seeing the ! operator used for non boolean variables. Here is an example of code not used in.

         


        
5条回答
  •  暖寄归人
    2020-12-03 11:25

    Any falsy value will satisfy the if(!insert_variable_here) condition, including:

    • false
    • null
    • undefined
    • The empty string ''
    • The number 0
    • NaN

    If callback return evaluates any of those values, the condition will be satisfied.

    Even though null != false, the following will give you an alert:

    x = null;
    if(!x) {
        alert('"!null" does evaluate to true');
    }
    

    Regardless of whether or not null != false makes sense to you or anyone else, the point is that in JavaScript null is a falsy value, and thus a value that would satisfy the condition in my first bit of code listed above. This, it seems, is the question you have asked--not, rather, if null should or should not == false.

提交回复
热议问题