Loose equality in JS in a powerful tool that allows you to loosely compare different values. If the types of the values don’t match, JavaScript will do a typecast (most often to a string type) and then do the comparison.

First of all, remember that loose equality is written as double equals == and it’s different from strict equality in JavaScript where you immediately get false if the operand types don’t match.

Main rules of loose equality in JS

  • loose equality operator == compares two values and returns the result of comparison (true or false)
  • if the types of two values don’t match, they will be converted to the same type automatically
  • the conversion to the same type doesn’t change the variable values

Examples of loose comparison with type conversion in JS

console.log(3 == '3'); // true
console.log(3 == '3'); // true
console.log(0 == '');  // true

console.log(0 == null);  // false
console.log(0 == undefined); // false
console.log(null == undefined); // true

console.log(new Number(3) == 3); // true
console.log(new Number(3) == '3'); // true

console.log(false == 0); // true
console.log(false == '0'); // true
console.log(true == 'hello'); // false
console.log(true == '1'); // true
console.log(true == 'true'); // false