the coerce equality operator (==)

Javascript is very handy and developer friendly, it is also a weak typed language, meaning that you are not forced to declare types for variables and you never know what type a variable is as its type can change

for example

var x = {};
    x = [];

it is perfectly legal.

The problem with weak typed languages, not only JavaScript, is that the interpreter can only compare variables of the same type, so it will try to convert both terms to be the same, this is called type coercion

Type Coercion usually results in unlogical situations.

""        ==   "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

the strict equality operator (===)

This operator is much more strict, it will compare the value and the type of variables.

The strict equality operator does not perform type coercion so it behaves in a more logical way

""        ===   "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

You can also use it to compare objects, but remember that the objects must be the same a new instance of the same object will not pass the comparison

var x = {};
var y = {};
var z = x;

x === y;    //false
z === x;    //true

So it is highly recommended that you only use the strict comparison operator, if you need to coerce types you should do it explicitly and never leave it to the interpreter

the order matters

The order of the comparison terms matters, you can avoid lots of weird bugs by following a simple rule

Whenever possible always put scalars/primitive types on the left of the comparison

if (x = 5) {
    alert('x is 5');

Can you spot the error?

This typo occurs very often, it is easy to miss a = and instead of comparing you assign a value. You have no idea you missed the =, the expression always evaluates to true and finding the error can take a long time.

if instead you place the primitive type on the left side of the comparison, you will get an error thrown, making debuging extremely simple and fast.

// this throws an error, because you can not assign a variable to a primitive type
if (5 = x) {
    alert('x is 5');