What is the difference between '==' and '===' operators in JavaScript? [duplicate]

8

I would like to know the difference between the two operators that would be:

(1): ==

(2): ===

If possible, I would also like to understand the use of their opposite operators in this case:

(3): !=

(4): !==

What would be the difference between the operators:

1:

if (foo == "foo")

2:

if (foo === "foo")

And what would be the difference between opposing operators:

3:

if (foo !== "foo")

4:

if (foo != "foo")

Could anyone tell me?

    
asked by anonymous 30.01.2014 / 17:01

4 answers

16

The difference is that if you use == there will be a coercion of the value so that both sides of the expression have the same type.

In the case of === there will be no coercion and so the code below will give false:

if(1 === '1')
    console.log('igual');
else
   console.log('diferente');//Esta será a resposta

If we only use == , there will be a coercion so that both are the same type and equal.

if(1 == '1')
    console.log('igual');//Esta será a resposta
else
   console.log('diferente');

Another example:

if(0 == '')
    console.log('igual');//Esta será a resposta
else
   console.log('diferente');

In case '' is considered a falsey value, which can be considered false even if it does not have the false value.

In the case below the correct message is given, which are different:

if(0 === '')
    console.log('igual');
else
   console.log('diferente');//Esta será a resposta

Edited

Here are some other values that can result in strange cases in logical comparison in javascript :

They give false:

0
''
' '
null
undefined
NaN
    
30.01.2014 / 17:04
6

== makes value-only comparison

=== does value and type comparison

if (1 == "1") // retorna true
if (1 === "1") // retorna false

Same thing with =! and ==! only the command is negation, returns true if the value is different and / or the type is also different.

if (1 != "1") // retorna false
if (1 !== "1") // retorna true
    
30.01.2014 / 17:16
2

The difference is that the value type is checked.

Ex:

var foo = "10";

console.log(foo == "10"); //true
console.log(foo === 10); //false
    
30.01.2014 / 17:08
1

== tests if it is equal to === tests if it is equal and of the same type

    
30.01.2014 / 17:24