DEV Community

TinoMuchenje
TinoMuchenje

Posted on • Updated on

Understanding Javascript equality == vs ===

Loose equality using ==

This operator compares two values for equality. (==) does not care about data types as it implicitly converts the value.

Example

'2' == 2 // true
'' == 0 // false
0 == '' // true

false == '0' // true
false == 'false' // false

' \t\r\n ' == 0 // true
Enter fullscreen mode Exit fullscreen mode

Strict equality using ===

Is very strict and cares about the datatypes.

Value conversion does not happen in this instance. If the values have a different type they are evaluated as false

Example

'2' === 2 //false
'' === 0 //false

//Comparing operands of the same Type
console.log("hello" === "hello");   // true
console.log("hello" === "hola");    // false

console.log(3 === 3);               // true
console.log(3 === 4);               // false

console.log(true === true);         // true
console.log(true === false);        // false

console.log(null === null);         // true


Enter fullscreen mode Exit fullscreen mode

Strict equality makes your code more robust there are no underlying value changes that may after your conditions.

Rules

  • If the operands are of different types, return false.
  • If both operands are objects, return true only if they refer to the same object.
  • If both operands are null or both operands are undefined, return true. -If either operand is NaN, return false. (Numbers must have the same numeric values. +0 and -0 are considered to be the same value.)
  • Strings must have the same characters in the same order.
  • Booleans must be both true or both false.

Alt Text

Reference [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness]

Discussion (0)