In this tutorial, you will learn how to use JavaScript comparison operators to compare two values.
To compare two values, you use the comparison operators. The following table illustrates the JavaScript comparison operators:
A comparison operator returns a Boolean value indicating that the comparison is true or not. See the following example:
let r1 = 20 > 10; // true
let r2 = 20 < 10; // false
let r3 = 10 == 10; // true
The comparison operator takes at least two values (or operands). If one of the two values has a different type, JavaScript will perform a conversion based on specific rules before comparing them. We will discuss each rule in detail in the following sections.
If the operands are numbers, JavaScript will perform a numeric comparison. For example:
let a = 10,
b = 20;
console.log(a >= b); // false
console.log(a == 10); // true
This example is straightforward. the variable a
is 10
, b
is 20
. The a>=b
expression returns and a==10
expression returns true
.
If the operands are strings, JavaScript compares the character codes numerically one by one in the string.
let name1 = 'alice',
name2 = 'bob';
let result = name1 < name2;
console.log(result); // true
console.log(name1 == 'alice'); // true
Because JavaScript compares character codes in the strings numerically, you may receive an unexpected result, for example:
let f1 = 'apple',
f2 = 'Banana';
let result = f2 < f1;
console.log(result); // true
In this example, f2
is less than f1
because the letter B
has the character code 66
while the letter a
has the character code 97
.
To fix this, you must first convert strings into a common format, either lowercase or uppercase and then perform comparison as follows:
let result2 = f2.toLowerCase() < f1.toLowerCase();
console.log(result2); // false
Note that the toLowerCase()
is a method of the String object that converts the string itself to lowercase.
#javascript #programming #developer #web-development