JS Comparison Operators

JavaScript

Share

In this tutorial we will learn about JavaScript comparison operators.

We use the comparison operator when we want to execute a set of code when the condition is satisfied.

This is commonly used in conditional statements and loops.

We will learn about conditional statement and loop in their respective tutorial.

Following is a list of conditional operators.

Operator Symbol Example
Is equal to == x == y
This will return true if value on both sides are equal to each other.
Is not equal to != x != y
This will return true if value on both sides are not equal to each other.
Is equal to and of same type === x == y
This will return true if value on both sides are equal to each other and of the same type.
Is not equal to or not of same type !== x !== y
This will return true if value on both sides are not equal to each other or not of same type.
Is greater than > x > y
This will return true if value on left side is greater than the value on the right side.
Is less than < x < y
This will return true if value on left side is less than the value on the right side.
Is greater than or equal to >= x >= y
This will return true if value on left side is greater than or equal to the value on the right side.
Is less than or equal to <= x <= y
This will return true if value on left side is less than or equal to the value on the right side.

Is equal to

In the following example we are checking whether x is equal to y.

var x = 10;
var y = 20;

console.log(x == y);	//this will print false

Is not equal to

In the following example we are checking whether x is not equal to y.

var x = 10;
var y = 20;

console.log(x != y);	//this will print true

Is equal to and of same type

In the following example we are checking whether x is equal to and of same type as y.

var x = 10;
var y = 10;

console.log(typeof x);	//this will print number
console.log(typeof y);	//this will print number
console.log(x === y);	//this will print true

We use the typeof operator to check the type.

Is not equal to or not of same type

In the following example we are checking whether x is not equal to or not of same type as y.

var x = 10;
var y = "10";

console.log(typeof x);	//this will print number
console.log(typeof y);	//this will print string
console.log(x !== y);	//this will print true

Is greater than

In the following example we are checking whether x is greater than y.

var x = 20;
var y = 10;

console.log(x > y);	//this will print true

Is less than

In the following example we are checking whether x is less than y.

var x = 20;
var y = 10;

console.log(x < y);	//this will print false

Is greater than or equal to

In the following example we are checking whether x is greater than or equal to y.

var x = 20;
var y = 10;

console.log(x >= y);	//this will print true

Is less than or equal to

In the following example we are checking whether x is less than or equal to y.

var x = 20;
var y = 10;

console.log(x <= y);	//this will print false