JS Tutorial



JS COMPARISON


JavaScript Comparisons 🔍

In JavaScript, comparison operators are used to compare two values. The result of a comparison is a boolean value: true or false.

💡 Comparison Operators

Here are the most common comparison operators in JavaScript:

  • Equal to: ==
  • Strict equal to (compares both value and type): ===
  • Not equal to: !=
  • Strict not equal to: !==
  • Greater than: >
  • Greater than or equal to: >=
  • Less than: <
  • Less than or equal to: <=
// Example comparisons
let x = 5;
let y = "5";
console.log(x == y);   // true (loose equality)
console.log(x === y);  // false (strict equality)
console.log(x != y);   // false
console.log(x !== y);  // true
console.log(x > 3);    // true
console.log(x < 10);   // true
  

🧑‍🏫 Live Example: Strict and Loose Equality

Enter values to check equality

📌 Why Use Strict Equality?

In JavaScript, the strict equality operator (===) is recommended over the loose equality operator (==) because it compares both the value and the type. The loose equality operator may produce unexpected results due to type coercion.

Example:

// Loose equality example:
console.log(5 == "5");  // true (coerces string to number)

// Strict equality example:
console.log(5 === "5"); // false (different types)
  

⚠️ Important Considerations

  • Loose equality: JavaScript will convert the values to the same type before comparing them.
  • Strict equality: Compares values and types without any conversion.
  • Be careful when comparing null and undefined. They are loosely equal but not strictly equal.

🔍 Use Cases

  • Form validation (checking if inputs are equal)
  • Checking user authentication credentials
  • Comparison of numerical values in algorithms
Note: Always prefer using === to avoid unexpected results due to type coercion.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review