JavaScript Comparison Operators

After assignment and math operators, the third set of operators we want to introduce is comparison operators or logical operators.

Comparison operators always return a boolean, a value that's true or false.

Those are disequality comparison operators:

Operator Description
= Assignment x=5; // assigns 5 to x
! Not, if not(false) is true.
|| OR, is (x==5) OR (y==5)
&& And, is (x==5) AND (y==5)
< Less than. is x less than 5?
<= Less than or equal. is x less than or equal to 5?
> Greater than. is x greater than 5?
>= Greater than or qual. is x greater than or equal to 5?

let a = 2;
a >= 1;//true

In addition to those, we have 4 equality operators. They accept two values, and return a boolean:

Operator Description
== Equality, is x==5?
=== Identity, is x 5 and a number as well?
!= Not equal, is x unequal to 5?
!== Not identical, is x unequal to the Number 5?

Let Explain some useful tactice here, Javascript supports equality checking == and identity checking ===

Equality checks for equality regardless of type. Therefore 25 as number and '25'as string will evaluate as true.

Identity checking checks not only for equality but type equality as well so 25 and '25'will evaluate as false because, while both are 25, one is a string and the other a number


let num1 = 25;
let num2 = "25";
num1 == num2; // true
num1 === num2; // false

Example


let num1 = 25;
let num2 = "25";
console.log(num1 == num2); // true
console.log(num1 === num2); // false

Note that we also have == and != in JavaScript, but I highly suggest to only use === and !==because they can prevent some subtle problems.


let num1 = 25;
let num2 = "25";
num1 !== num2; // true