What is the difference between the == and === operators in JavaScript?

115

I have the following code in JavaScript :

var x = 0;

if (x === false) {
  // não acessa
}

if (x == false) {
  // acessa
}
  • Why does the expression with the == operator return true and with the === operator return false ?
  • What is the difference between the two operators?
asked by Alicia Tairini 11.12.2013 в 16:58
source

10 answers

106

The == operator compares by "result" to say so, that is, as JavaScript is not strongly typed, it converts what you want to compare and verifies that:

if (true == 'true')  // aqui vai dar true
if (true == '1')     // aqui vai dar true
if (true == true)    // aqui vai dar true
if (true === 'true') // aqui vai dar false
if (true === '1')    // aqui vai dar false
if (true === true)   // aqui vai dar true

The operator === it compares the value and type, then it will only be true if it is exactly equal (value and type).

Response Completion:

  • See this post of StackOverflow in English that contains some additional examples.

  • I think the explanation was a bit flawed, next when the language is not typed it does not compare by type but by value, ie 15 is the same as "15" when language is not typed.

    But when you use === you force the code to compare type too, I recommend reading this article at Wikipedia

    a> for better understanding.

  • answered by 11.12.2013 / 17:01
    source
    42

    According to the ECMAScript , triple === means "equality strict ", that is, it only returns true if the operands are of the same type and value.

    To be more exact, the algorithm, in x === y comparison is:

    Se Type(x) é diferente de Type(y), retorna false.
    Se Type(x) é Undefined, retorna true.
    Se Type(x) é Null, retorna true.
    Se Type(x) é Number, então
        Se x é NaN, retorna false.
        Se y é NaN, retorna false.
        Se x é do mesmo valor numérico que y, retorna true.
        Se x é +0 e y é -0, return true.
        Se x é -0 e y é +0, retorna true.
        Retorna false.
    Se Type(x) é String, retorna true se x e y são exatamente a mesma sequência de caracteres (mesmo tamanho e mesmos caracteres nas posições correspondentes); caso contrário, retorna false.
    Se Type(x) é Boolean, retorna true se x e y são ambos true ou ambos false; caso contrário, retorna false.
    Retorna true se x e y referem-se ao mesmo objeto. Caso contrário, retorna false.
    
        
    answered by 11.12.2013 в 17:08
    23

    JavaScript has automatic type conversion, according to some not very intuitive rules . The == operator uses this conversion at both ends of the comparison. Since === requires that the two terms of the comparison be of the same type, in addition to having the same value.

    In this way, for example:

    "1" == 1; // true, mesmo com tipos diferentes
    "1" === 1; // false, justamente devido aos tipos diferentes
    
        
    answered by 11.12.2013 в 17:03
    23

    In JavaScript there are two pairs of equality operators: === and !== , and evil twins == and != (as described in JavaScript The Good Parts in> by Douglas Crockford).

    === and !==

    The first pair of operators, === and !== , works as == and !== in most programming languages, if the values compared with === have the same value and are the same type true is returned by the expression and if they are compared with !== false is returned.

    Examples using === and !==

    '' === '0'          // false
    0 === ''            // false
    0 === '0'           // false
    false === 'false'   // false
    false === '0'       // false
    false === undefined // false
    false === null      // false
    null === undefined  // false
    ' \t\r\n ' === 0    // false
    

    == and !=

    The second pair of operators, == and != , works as follows, when both values are of the same type, the evil twins behave like the other pair of operators ( === and !== ), but when the values compared are of different types they try to correct the values by converting them, which seems cool, but can produce difficult results to understand and make it difficult to maintain the code.

    Examples using == and !=

    '' == '0'          // false
    0 == ''            // true
    0 == '0'           // true
    false == 'false'   // false
    false == '0'       // true
    false == undefined // false
    false == null      // false
    null == undefined  // true
    ' \t\r\n ' == 0    // true
    

    A recommendation given by Douglas Crockford is to never use the evil twins, instead of using === and !== instead.

        
    answered by 30.12.2013 в 16:02
    17

    When you use the == operator and the types are different, Javascript internally converts to numbers. In this case, false when converted to number becomes 0 . In the case of the operator === , the two arguments must be exactly the same, in type and value, so the result is false.

        
    answered by 11.12.2013 в 17:04
    16

    Normally weakly typed languages are responsible for converting the data types.

    So when you use the == operator, the language does cast or type conversion for comparison of values.

    The === operator says to compare the data types and values being tested.

        
    answered by 11.12.2013 в 17:03
    13

    JavaScript has both strict and abstract comparisons.

    A strict comparison ( === ) is only true if the operands are of the same type and have the same value.

    The most commonly used comparison is the abstract ( == ), which converts the operands to the same type before comparing.

    Strings are compared based on lexicographical ordering, using Unicode values.

        
    answered by 17.01.2014 в 18:56
    11

    The == operator converts between types to check.

    An example is that true==1 and false=='' will both give true, even though they are comparisons of different data types.

    By using the === operator, you are forcing a data type such as true===1 and false==='' to give both false .

    Warning: NaN is an object in javascript. This means that {}=={} will be false, such as NaN==NaN .

    The MDN (Mozilla Development Network) website uses this 'trick' to detect NaN .

    One way to check if it's a number might look like this: valor+0==valor+0 . If value is not number, it results in false .

        
    answered by 31.01.2014 в 18:28
    10

    The Javascript problem is that it has poor typing, meaning it does type implied conversions. A '0' == 0 comparison results in true because the operator converts string to number in an attempt to "fix" the type difference.

    PHP has the same problem. I imagine that because of the origins on the Web, JS and PHP have opted for weak typing because all data coming from e.g. a web form is string, but many fields "mean" numbers.

    While Python has strong (though dynamic) typing and comparison between different types, it usually results in False.

    The === and !== operators make a "strong" comparison, ie according to strong typing rules, and return False for comparison between strings and numbers.

        
    answered by 08.02.2014 в 03:38
    8

    The === compares variables of the same type.
    The == follows rules like "true" == true, 1 == true, etc ..

    So use "strict" at the beginning of your function or file, this forces the use of === .

        
    answered by 11.12.2013 в 17:31