When would JavaScript == make more sense than ===?

后端 未结 4 2007
太阳男子
太阳男子 2021-01-01 17:22

As Which equals operator (== vs ===) should be used in JavaScript comparisons? indicates they are basically identical except \'===\' also ensures type equality

相关标签:
4条回答
  • 2021-01-01 17:53

    == compares whether the value of the 2 sides are the same or not.

    === compares whether the value and datatype of the 2 sides are the same or not.

    Say we have

    $var = 0;
    
    if($var == false){
      // true because 0 is also read as false
    }
    
    if(!$var){
      // true because 0 is also read as false
    }
    
    if($var === false){
      // false because 0 is not the same datatype as false. (int vs bool)
    }
    
    if($var !== false){
      // true becuase 0 is not the same datatype as false. (int vs bool)
    }
    
    if($var === 0){
      // true, the value and datatype are the same.
    }
    

    you can check http://www.jonlee.ca/the-triple-equals-in-php/

    0 讨论(0)
  • 2021-01-01 18:01

    The simple answer is that '==' makes more sense than '===' when you want type coercion to happen during comparisons.

    A good example would be numbers being passed in a URL query string. If for instance you have paginated content, and the page query parameter holds the current page number, then you could check for the current page with if (page == 1) ... even though page is actually "1", not 1.

    0 讨论(0)
  • 2021-01-01 18:08

    Consider a situation when you compare numbers or strings:

    if (4 === 4)
    {
      // true
    }
    

    but

    if (4 == "4")
    {
      // true
    }
    

    and

    if (4 === "4")
    {
      // false
    }
    

    This applies to objects as well as arrays.

    So in above cases, you have to make sensible choice whether to use == or ===

    0 讨论(0)
  • 2021-01-01 18:10

    I would suggest that there is no problem with using ==, but to understand when and why to use it (i.e. use === as a rule, and == when it serves a purpose). Essentially, == just gives you shorthand notation - instead of doing something like

    if (vble === 0 || vble === "" || vble === null || vble === undefined || vble === false) ...
    

    It's much easier to just write

    if (vble == false) ...
    

    (Or even easier to write)

    if (!vble) ...

    Of course there are more examples than just looking for "truthy" or "falsey" values.

    Really, you just need to understand when and why to use == and ===, I don't see any reason why not to use == where it fits better...

    Another example is using this shorthand to allow shorthand method calls:

    function func(boolOptionNotCommonlyUsed) {
      if (boolOptionNotCommonlyUsed) { //equiv to boolOptionNotCommonlyUsed == true
        //do something we rarely do
      }
      //do whatever func usually does
    }
    
    func(); //we rarely use boolOptionNotCommonlyUsed, so allow calling without "false" as an arg
    
    0 讨论(0)
提交回复
热议问题