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); // falsescore = 7
print(score == 10) # False
print(score != 10) # True
print(score > 5) # True
print(score < 5) # False
print(score >= 7) # True
print(score <= 6) # Falselet 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.
Logical Operators
Logical operators combine or invert boolean conditions. They are used to build compound conditions — checks that require more than one thing to be true at the same time, or where either of two things being true is enough.
For a broader introduction to operators, see Operators.
AND#
The AND operator returns true only when both conditions are true. If either is false, the result is false.
| Left | Right | Result |
|---|---|---|
true |
true |
true |
true |
false |
false |
false |
true |
false |
false |
false |
false |
int score = 7;
bool result = score > 5 && score < 10; // truescore = 7
result = score > 5 and score < 10 # Truelet score = 7;
let result = score > 5 && score < 10; // true
OR#
The OR operator returns true when at least one condition is true. It only returns false when both are false.
While Loop
A while loop repeats a block of code as long as a condition is true. Each time the block finishes, the condition is checked again. When it becomes false, the loop stops.
For a broader introduction to loops, see Loop.
┌─────────────────┐
│ check condition│◄──────┐
└────────┬────────┘ │
true │ false │
▼ ▼ │
┌────────────┐ exit │
│ loop body │───────────┘
└────────────┘Basic While Loop#
int count = 0;
while (count < 3)
{
Console.WriteLine(count);
count++;
}Output: 0, 1, 2. When count reaches 3, the condition count < 3 becomes false and the loop stops.