JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Comparisons


Comparison operators are fundamental in JavaScript. They allow developers to evaluate relationships between two values, making decisions based on those evaluations. These operators are used extensively in conditional statements, loops, and logical expressions, forming the backbone of decision-making in your code. Understanding comparisons thoroughly is essential for accurate and predictable program behavior.

This tutorial provides a detailed overview of JavaScript comparison operators, practical examples, common mistakes, best practices, and real-world applications.

Why Comparisons Are Important

Comparisons are crucial because they:

  • Allow programs to make decisions based on variable values.

  • Enable validation of user inputs or API data.

  • Control the flow of code through conditional statements like if...else or loops.

  • Support logical expressions in complex operations.

  • Help in filtering, sorting, and evaluating data dynamically.

Without comparison operators, your code would be unable to differentiate between different states or respond appropriately to varying conditions.

Types of Comparison Operators

JavaScript provides several comparison operators, each with specific behavior:

1. Equal (==)

Checks if two values are equal, performing type coercion if necessary.

let a = 5;
console.log(a == "5"); // true

Here, the string "5" is converted to a number before comparison, resulting in true.

2. Strict Equal (===)

Checks if two values are equal without type coercion.

console.log(a === "5"); // false
console.log(a === 5);   // true

Strict equality is generally recommended because it avoids unexpected results due to type conversion.

3. Not Equal (!=)

Checks if two values are not equal, performing type coercion.

console.log(a != "6"); // true
console.log(a != "5"); // false

4. Strict Not Equal (!==)

Checks if two values are not equal without type coercion.

console.log(a !== "5"); // true
console.log(a !== 5);   // false

5. Greater Than (>)

Checks if the left-hand value is greater than the right-hand value.

console.log(a > 3); // true
console.log(a > 5); // false

6. Less Than (<)

Checks if the left-hand value is less than the right-hand value.

console.log(a < 10); // true
console.log(a < 5);  // false

7. Greater Than or Equal (>=)

Checks if the left-hand value is greater than or equal to the right-hand value.

console.log(a >= 5); // true
console.log(a >= 6); // false

8. Less Than or Equal (<=)

Checks if the left-hand value is less than or equal to the right-hand value.

console.log(a <= 5); // true
console.log(a <= 4); // false

Practical Examples

Example 1: Checking User Age

let age = 20;

if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}

Example 2: Validating Credentials

let username = "Emma";
let input = "Emma";

if (input === username) {
  console.log("Username matches.");
} else {
  console.log("Incorrect username.");
}

Example 3: Price Comparison

let price = 50;
let budget = 100;

if (price <= budget) {
  console.log("You can buy this item.");
} else {
  console.log("Item is too expensive.");
}

Example 4: Range Check with Logical Operators

let score = 85;

if (score >= 75 && score <= 100) {
  console.log("You scored in the top range.");
} else {
  console.log("Score is below top range.");
}

Example 5: Using Comparisons with Ternary Operator

let temperature = 30;
let status = temperature > 25 ? "Hot" : "Cool";
console.log(status); // Hot

Example 6: Checking Multiple Conditions

let marks = 70;
let attendance = 80;

if (marks >= 50 && attendance >= 75) {
  console.log("Eligible for exam.");
} else {
  console.log("Not eligible for exam.");
}

Common Mistakes

  • Using == instead of === and being surprised by type coercion.

  • Forgetting to combine conditions properly using && or ||.

  • Misunderstanding operator precedence in complex expressions.

  • Comparing different data types without realizing JavaScript will perform type conversion.

  • Relying on truthy/falsy behavior without explicit conversion.

Best Practices

  • Prefer === and !== over == and != to avoid unintended type coercion.

  • Use parentheses to clarify complex logical conditions.

  • Combine comparisons with logical operators carefully to avoid unexpected results.

  • Validate inputs before comparison to ensure correct data types.

  • Document assumptions about variable types to improve readability.

Real-World Applications

  • Validating user input in forms (age, email, password strength).

  • Comparing scores, grades, or rankings in applications.

  • Filtering and sorting arrays of data.

  • Conditional rendering in web applications.

  • Controlling access based on permissions or roles.

Summary of JS Comparisons

Comparison operators in JavaScript allow developers to evaluate relationships between values and make decisions based on those evaluations. From strict equality and inequality to greater-than or less-than comparisons, these operators are used extensively in conditional statements, loops, and logical expressions. Proper use of === and !==, combined with careful handling of logical operators and type checking, ensures accurate and predictable outcomes. Mastering comparisons is essential for creating dynamic, interactive, and reliable web applications.


Practice Questions

Q1. What is the difference between == and === in JavaScript?

Q2. How do you compare whether two values are not equal and of different types?

Q3. What will 0 == false return and why?

Q4. How can you compare two numbers and check if one is greater or equal to the other?

Q5. Which operator would you use to check strict inequality?

Q6. How does JavaScript compare strings using < or > operators?

Q7. What is the result of "5" == 5 and why?

Q8. How do you compare whether a value is less than or equal to another in an if condition?

Q9. What happens when you compare two arrays like [1,2] === [1,2]?

Q10. Why is it recommended to use === over == in most cases?


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top