What is the difference between the == and === Javascript operators?

Asked

Viewed 34,548 times

143

I have the following Javascript code:

var x = 0;

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

if (x == false) {
  // acessa
}

Why the expression with the operator == returns true and with the operator === returns false?

What is the difference between the two operators?

  • 4

    Note that an elegant way (in my view) of writing code like this is if (!x) { /* acessa */ }

  • 4

    @Camilomartin Yes, but !x gives true for some values that x === false would false, as x = 0.

10 answers

134


The operator == compares by "result" so to speak, in other words, since Javascript is not strongly typed it converts what you want to compare and checks:

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 === he compares the value and the type, so it’ll just be true if it is exactly the same (value and type).


Complement to the answer:

  1. Behold this post Stackoverflow in English containing some additional examples.

  2. I think the explanation was a little deficient, next when the language is not typed it does not compare by type but by value, ie 15 is the same thing as "15" when the language is not typed.

    But when you use the === you force the code to compare the type as well, I recommend reading this article on Wikipedia for better understanding.

  • 8

    NaN === NaN //false <3 JS

  • 28

    NaN === NaN return false is not a weirdness of Javascript: It is something expected, and even specified by the IEEE 754 standard that defines floating point numbers. Float::NAN == Float::NAN (Ruby) and float("NaN") == float("NaN") (Python) also return false.

  • 4

    It is even a way to detect Nan, without using isNaN(x): compare a variable with itself.

  • 2

    The logic is the same for !== and != correct?

  • 2

    @Joaopaulo is not, !== will compare by type and value and != only by value. That is, 1 !== '1' // true and 1 != '1' //false

52

According to the specification of Ecmascript, the triple === means "strict equality", ie only returns true if the operands are of the same type and value.

To be more exact, the algorithm, in a comparison x === y 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.
  • 1

    @Marconi Once he has tested the types of x and y are equal (passed the first test), two objects of the type Undefined or Null are considered equal. That is to say, undefined === undefined and null === null.

  • Thanks @Augusto, for me this is the best answer, I’ve left my +1!

31

In Javascript there are two pairs of equal operators: === and !==, and the evil twins (evil Twins) == and != (as described in Javascript The Good Parts by Douglas Crockford).

=== and !==

The first pair of operators, === and !==, works like the == and !== in most programming languages. So if the values compared with === have the same value and are of the same type, the expression will result in true, already the !== indicates the opposite to that statement.

Examples using === and !==

2 === 2             // true
'ola' === 'ola'     // true
'' === '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 !=, work as follows. When both compared 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 through a conversion before making the comparison. This sounds cool, but can generate hard-to-understand results and makes it difficult to maintain code.

Examples using == and !=

2 == 2             // true
'ola' == 'ola'     // true
'' == '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 never to use evil twins, in their place always use === and !==.

28

Javascript has automatic conversion of types, second some rules not very intuitive. The operator == uses this conversion at both ends of the comparison. Already === requires the two terms of the comparison to be of the same type and have the same.

That way, for example:

"1" == 1; // true, mesmo com tipos diferentes
"1" === 1; // false, justamente devido aos tipos diferentes

20

Typically weakly typed languages undertake the conversion of data types.

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

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

20

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

18

Javascript has both comparisons strict and abstract.

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

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

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

16

The operator == converts between types to check.

One example is that true==1 and that false=='' will give both true, despite being comparisons of different data types.

Using the operator ===, is "forcing" a type of data, such as true===1 and false==='' give both false.

Warning: NaN is a javascript object. This means that {}=={} will be fake, just like NaN==NaN.

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

A way to check if it’s a number can be like this: valor+0==valor+0. If value is not number, results in false.

  • 1

    Please add the MDN documentation reference.

15

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

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

Python has strong typing (although dynamic) and comparison between different types results, as a rule, in False.

Operators === and !== make "strong" comparison, that is, according to the strong typing rules, and return False for comparison between strings and numbers.

9

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

Therefore, use "use Strict" at the beginning of your function or file, this forces the use of ===.

  • No, "use Strict" does not serve for this. It serves to generate error when trying to use an undeclared variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.