/

Understanding JavaScript Comparison Operators

Understanding JavaScript Comparison Operators

In JavaScript, comparison operators are used to compare two values and determine their relationship. These operators return a boolean value, either true or false, based on the comparison result. This article will cover the basic comparison operators in JavaScript and provide examples of their usage.

Less Than (<) Operator

The less than operator (<) checks if the value on the left is smaller than the value on the right. It returns true if the condition is met, otherwise false. For example:

1
2
3
4
5
const a = 5;
const b = 10;

console.log(a < b); // Output: true
console.log(b < a); // Output: false

Less Than or Equal To (<=) Operator

The less than or equal to operator (<=) checks if the value on the left is smaller than or equal to the value on the right. It returns true if the condition is met, otherwise false. For example:

1
2
3
4
5
6
7
const a = 5;
const b = 10;
const c = 5;

console.log(a <= b); // Output: true
console.log(b <= a); // Output: false
console.log(a <= c); // Output: true

Greater Than (>) Operator

The greater than operator (>) checks if the value on the left is greater than the value on the right. It returns true if the condition is met, otherwise false. For example:

1
2
3
4
5
const a = 5;
const b = 10;

console.log(a > b); // Output: false
console.log(b > a); // Output: true

Greater Than or Equal To (>=) Operator

The greater than or equal to operator (>=) checks if the value on the left is greater than or equal to the value on the right. It returns true if the condition is met, otherwise false. For example:

1
2
3
4
5
6
7
const a = 5;
const b = 10;
const c = 5;

console.log(a >= b); // Output: false
console.log(b >= a); // Output: true
console.log(a >= c); // Output: true

Comparison Operators with Strings

When comparing strings using these operators, JavaScript checks the letter ordering based on Unicode values. The Unicode value of a letter determines its position in the ordering. The greater the Unicode value, the greater the letter is to the operator when comparing. For example:

1
2
3
4
5
const str1 = 'apple';
const str2 = 'banana';

console.log(str1 < str2); // Output: true
console.log(str2 < str1); // Output: false

Unicode values for characters can be found in the list of Unicode Codes for characters on Wikipedia.

Conclusion

Understanding JavaScript comparison operators is essential for writing effective and logical code. By utilizing these operators, you can compare numbers or strings and make decisions based on the comparison results. Remember to consider the Unicode values for string comparisons.