HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Comparison

Comparison operators are used in logical statements to determine equality or difference between variables or values. The result of a comparison is always a boolean value: true or false.


Comparison Operators Table

Here are the comparison operators available in JavaScript:

Operator Description Example
== Equal to (checks value only) x == 8
=== Strict equal to (checks value and type) x === "8"
!= Not equal to x != 8
!== Strict not equal to x !== "8"
> Greater than x > 8
< Less than x < 8
>= Greater than or equal to x >= 8
<= Less than or equal to x <= 8

Equal vs. Strict Equal

The most important part of comparison in JavaScript is understanding the difference between == and ===.

1. Equal (==)

The == operator compares two values for equality after converting them to a common type (type coercion).

let x = 5;
console.log(x == 5);    // true
console.log(x == "5");  // true (string "5" is converted to number 5)

2. Strict Equal (===)

The === operator (also called "identity" or "triple equal") compares both the value and the data type. No conversion happens.

let x = 5;
console.log(x === 5);   // true
console.log(x === "5"); // false (because one is a number and the other is a string)
Best Practice: Always use === and !==. They are more predictable and prevent hidden bugs caused by automatic type conversion.

Relational Operators

These operators are used to compare numeric values (though they also work with strings using alphabetical order).

let age = 18;

console.log(age > 15);  // true
console.log(age < 20);  // true
console.log(age >= 18); // true
console.log(age <= 10); // false

Comparison in Logical Decisions

Comparison operators are most commonly used inside if statements to control the flow of the program.

let hour = 14;

if (hour < 18) {
    console.log("Good day!");
}

Key Points to Remember

  • The result of a comparison is always true or false
  • == compares values only; === compares values and types
  • Relational operators (>, <, etc.) are standard math comparisons
  • Comparison operators are the foundation of decision-making in code