Skip to main content

Comparison Operators

Introduction to Comparison Operators in JavaScript

Comparison operators are used in logical statements to determine equality or difference between variables or values. These operators return a boolean value, either true or false.

In JavaScript, there are several types of comparison operators. Let's dive into them one by one.

Equality (==)

The == operator checks if the values of two operands are equal or not. If they are equal, it returns true. If not, it returns false.

let x = 5;
let y = '5';

console.log(x == y); // Returns true

In the above example, even though x is a number and y is a string, the == operator considers them equal because it does not check the datatype.

Inequality (!=)

The != operator checks if the values of two operands are not equal. If they are not equal, it returns true. If they are equal, it returns false.

let x = 5;
let y = '5';

console.log(x != y); // Returns false

Like the == operator, the != operator does not check the datatype of the operands.

Identity / strict equality (===)

The === operator checks if the values of two operands are equal, AND they are of the same type. If both conditions are satisfied, it returns true. Otherwise, it returns false.

let x = 5;
let y = '5';

console.log(x === y); // Returns false

In this example, although x and y have equal values, they are of different datatypes. Hence, the === operator returns false.

Non-identity / strict inequality (!==)

The !== operator checks if the values of two operands are not equal, OR they are not of the same type. If either of these conditions is satisfied, it returns true. Otherwise, it returns false.

let x = 5;
let y = '5';

console.log(x !== y); // Returns true

Here, x and y are not of the same type. Thus, the !== operator returns true.

Greater than (>), Less than (<), Greater than or equal to (>=), Less than or equal to (<=)

These operators are pretty straightforward. They compare the values of two operands and return true or false accordingly.

let x = 5;
let y = 10;

console.log(x > y); // Returns false
console.log(x < y); // Returns true
console.log(x >= y); // Returns false
console.log(x <= y); // Returns true

In JavaScript, you can also compare strings using these operators. The comparison is based on the Unicode value of characters.

let x = 'apple';
let y = 'banana';

console.log(x < y); // Returns true

In this example, 'apple' is less than 'banana' because the Unicode value of 'a' is less than 'b'.

Conclusion

Understanding comparison operators is fundamental to writing logical statements in JavaScript. These operators allow you to compare values and make decisions based on the results of those comparisons. As you continue your JavaScript learning journey, you'll find these operators to be essential tools in your programming toolbox.