DEV Community

Tino Joel Muchenje
Tino Joel Muchenje

Posted on • Edited on

3 3

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]

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay