ðÿ “” == “vs.” === “In JavaScript: Understanding the main differences | By Samudhra Gopal | March 2025
2 mins read

ðÿ “” == “vs.” === “In JavaScript: Understanding the main differences | By Samudhra Gopal | March 2025


Stackademic

When you compare in JavaScript, “== – (Loose equality) And “===” (strict equality) behave differently. Understanding these differences is crucial to avoid bugs in your code.

ðÿ “¹Key difference between” == “and” === “

ð `« obrottingpanding == (loose equality)

How works “==”

  • Converts the two values ​​into common type before the comparison.
  • Can lead to unexpected results if they are not used with care.

Case examples:

Example in the code:

console.log(5 == "5"); //true (string "5" is converted to number 5)
console.log(0 == false); //true (false)
console.log("" == false); //true (empty string is converted to 0)
console.log(null == undefined); //true (special case)

– Be careful when using “==! Type conversion can sometimes produce unexpected results.

ðÿ ”¹ Organization chart:

To start
A”,
 – ¼
Check if the types are the same?
A”,
 “œ” â – ¼ “€ â” € â “yes” € â “€ â € – compare the values ​​directly
A”,
 “â” € no »€ â € â
A”,
 – ¼
Compare the converted values
A”,
 – ¼
Returns “True” or “False”

ðÿ “to understand” === “(strict equality)

How === works:

  • No type conversion is made.
  • The values ​​must be identical both in type and in value.

Examples Case:

Example in the code:

console.log(5 === "5"); //false (string "5" is not the same type as number 5)
console.log(0 === false); //false (boolean false is not the same as number 0)
console.log("" === false); //false (string is not a boolean)
console.log(null === undefined); //false (different types)

Âe … === is the favorite choice for most cases because it avoids involuntary type conversion.

ðÿ ”¹flowchart:

To start
A”,
 – ¼
Check if the types are the same?
A”,
 “œ” â – ¼ “€ â” € â “yes” € â “€ â € – compare the values ​​directly
A”,
 “” â “€ no” € â “€ â -º” False “return (no type conversion!)

Scenario of the real world: Bug of the connection system!

 œ Using == (bug)

let password = "";
if (password == false) {
console.log("password cannot be empty!");
}

ðÿ ”¹Proble: From “€ œ” == False is trueThe system thinks that an empty password is not valid.

Âœ… Use === (Corrective)

if (password === false) {
console.log("password is exactly `false`, not empty.");
}

Now only an explicit FAKE The value will trigger the condition.

ðÿš € when using == vs ===?

ðÿ ”less practice:

Always prefer === Unless you intentionally Need type conversion.

ðÿ “Table

ðÿ ”Šconnclusion:

  • To use === For strict and predictable comparisons.
  • To use== Only when necessary, but be aware of type coercion.
  • Understanding these differences can prevent unexpected bugs in JavaScript applications.

Before leaving:



Grpahic Designer