What’s the difference between == and === ?

Short Answer

== only compares values

=== compares values + type

1
2
3
4
5
  var a = '1',
    b = 1;

    a == b;   // true
    a === b;  // false

Let’s talk about it

People say Javascript is an easy-to-lean language. The most common bad practice I found reading javascript code is the operator == in place of ===. Someone could say it’s simple to manage a script without care about types. In my opinion it just makes the code crap!! (the only exception it’s the a == null that checks if a is null or undefined, but still sometimes we would like to know if it is exactly null)

A common usage of javascript is DOM manipulation. Let’s say we have a numerical value in a div, for example: test

1
  <div id="first-number">1</div>

And we want to add that number to ‘2’:

1
2
3
4
		var first_num = document.getElementById("first-number").innerHTML;
		var second_num = 2;
		var result = first_num + second_num; // 12
	

The result will be 12!! Indeed the first_num element is a string, and javascript being a loosely typed and dynamic language will convert the second_num in string and perform a string concatenation in place of a sum.

P.S. In other programming languages the result could be different

Resources: