DEV Community

TinoMuchenje
TinoMuchenje

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]

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay