📜 ⬆️ ⬇️

== and === differences in javascript

Immediately I will warn you, yes, the article is a little incorrect, welcome to the comments, there are quite good clarifications).

Good day.


There are two similar operators in JavaScript: == and ===. If you do not know their differences, it can turn into a bunch of errors. So I decided to open this topic. What exactly is the difference between == and ===, how they work, why it happens, and how to avoid mistakes.

Operator == compares for equality, but === for identity. The operator’s === plus is that he does not give two values ​​to the same type. Because of this, it is usually used.
')
abc == undefined; // true,  abc = undefined | null abc === undefined; // true -   abc = undefined! 

 abc == false; // true,  abc = false | 0 | '' | [] abc === false; // true,   abc = false! 

After all, confusing false and 0 (or '', or []) is hardly very good.

Of course:
 5 === 5; // true true === true; // true 'abc' === 'abc'; // true 


And now an interesting example.
 5 == 5; // true 5 === 5; // true new Number(5) == 5; // true new Number(5) === 5; // false! 


Why it happens? Yes, any number is an object of class Number. But you can imagine the number as a number - some constant. It is declared once, and always identical to itself. But at the same time, declaring a new object of class Number is equal to it in value, but not identical (since these are two completely different objects of class Number).

Arrays / Objects


But for arrays and objects, both operators work in the same way, comparing identity:
 var a = {}; a == {}; // false a === {}; // false a == a; // true a === a; // true 


To compare arrays and objects, you can write a special function:
 function isEq(a, b){ if(a == b) return true; for(var i in a){ if(!isEq(a[i], b[i])) return false; } for(var i in b){ if(!isEq(a[i], b[i])) return false; } return true; } 

A little carelessly, two loops, and forgot about hasOwnProperty ; Well, come down.

This <-


There is another underwater rock. This is a transfer to this.
 (function(){ this == 5; // true this === 5; // false }).call(5); 


Here is such a moment. Should not forget about it.

Total ...


And now let's imagine that we are writing our superframe, actively using the === operator instead of == simply because it is more beautiful, and someone finds some bugs here.
 func(new Number(5)); (function(){ func(this); }).call(5); 


It seems that such examples are not viable? You are welcome!

jQuery:
 $.each([1, 2, 3, 4, 5], function(){ func(this); }); 


Well, or wanted to expand the figure.
 var Five = new Number(5); Five.a = 2; //  ,   5   //  - ... func(Five); 


That's all, I hope someone will be useful. Thanks for attention.

UPD. Thanks for the link vermilion1 , JS Garden .

Source: https://habr.com/ru/post/138272/


All Articles