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

后端 未结 5 446
小鲜肉
小鲜肉 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:49

    Every variable and object can be equated to true or false. In the case of objects, undefined is false, anything else is true.

    This actually gives some interesting edge cases http://www.ejball.com/EdAtWork/2005/02/15/JavaScriptWhatIsTrue.aspx

    One that kinda blows my mind null != false evaluates to true

    UPDATE

    Note for all those people bashing me in the comments the ECMAScript specification on page 43 defines the toBoolean conversion of null as false. As we're only using a == and not doing a type check with === I find it very reasonably that I would expect null == false to evaluate to true.

    That specification was published June this year so maybe this is a change, but it appears the specification writers come down on my side of the table in this debate.

提交回复
热议问题