Comparison operators are used in logical statements to determine equality or difference between variables or values. JavaScript supports several comparison operators, including:
==
(Equal to)===
(Equal value and equal type)!=
(Not equal)!==
(Not equal value or not equal type)>
(Greater than)<
(Less than)>=
(Greater than or equal to)<=
(Less than or equal to)
How to Use Comparison Operators
Here’s a brief explanation of how each operator works:
Equal to (==
)
The ==
operator checks if the values of two operands are equal or not. If they are equal, it returns true.
let x = 5;
console.log(x == 5); // true
Equal Value and Equal Type (===
)
The ===
operator checks if the values of two operands are equal or not, and also checks the types.
let x = 5;
console.log(x === "5"); // false
Not Equal (!=
)
The !=
operator checks if the values of two operands are not equal. If they are not equal, it returns true.
let x = 5;
console.log(x != 4); // true
Not Equal Value or Not Equal Type (!==
)
The !==
operator checks if the values of two operands are not equal, or if their types are not equal.
let x = 5;
console.log(x !== "5"); // true
Greater Than (>
)
The >
operator checks if the value of the left operand is greater than the value of the right operand. If it is, it returns true.
let x = 5;
console.log(x > 4); // true
Less Than (<
)
The <
operator checks if the value of the left operand is less than the value of the right operand. If it is, it returns true.
let x = 5;
console.log(x < 6); // true
Greater Than or Equal To (>=
)
The >=
operator checks if the value of the left operand is greater than or equal to the value of the right operand. If it is, it returns true.
let x = 5;
console.log(x >= 5); // true
Less Than or Equal To (<=
)
The <=
operator checks if the value of the left operand is less than or equal to the value of the right operand. If it is, it returns true.
let x = 5;
console.log(x <= 5); // true
Using JavaScript’s comparison operators is fundamental to comparing values in your code. They are essential tools in every developer’s toolkit.