Comparison Operators

Comparison operators compare two values and produce a boolean result — either true or false. They are used to build conditions in if/else statements, loops, and anywhere a decision needs to be made.

For a broader introduction to operators, see Operators.

Operators#

Operator Meaning Example
== Equal to score == 10
!= Not equal to score != 10
> Greater than score > 5
< Less than score < 5
>= Greater than or equal to score >= 5
<= Less than or equal to score <= 5

Examples#

int score = 7;

Console.WriteLine(score == 10);  // false
Console.WriteLine(score != 10);  // true
Console.WriteLine(score > 5);    // true
Console.WriteLine(score < 5);    // false
Console.WriteLine(score >= 7);   // true
Console.WriteLine(score <= 6);   // false
score = 7

print(score == 10)  # False
print(score != 10)  # True
print(score > 5)    # True
print(score < 5)    # False
print(score >= 7)   # True
print(score <= 6)   # False
let score = 7;

console.log(score === 10);  // false
console.log(score !== 10);  // true
console.log(score > 5);     // true
console.log(score < 5);     // false
console.log(score >= 7);    // true
console.log(score <= 6);    // false

Note: JavaScript uses === (strict equality) instead of ==. Using == in JavaScript performs type coercion and can produce unexpected results. Always use === for comparisons.

Common Mistakes#

Using = instead of == score = 10 assigns the value 10 to score. score == 10 checks if score equals 10. These are completely different operations. In many languages, using = inside a condition is a compile error. In others it silently does the wrong thing.

Using == instead of === in JavaScript JavaScript’s == performs type coercion — it tries to convert values before comparing them. "1" == 1 is true in JavaScript. Use === to compare both value and type, which is almost always what you want.

Off-by-one errors with boundaries score > 5 and score >= 5 behave differently when score is exactly 5. The first excludes it, the second includes it. Always check which boundary behaviour you actually need.

Comparing strings with > or < Comparing strings with greater/less than operators compares them alphabetically by character code, not by length or numeric value. "10" < "9" is true because "1" comes before "9". Parse strings to numbers before comparing numerically.

Resources#