JS Logical Operators

JavaScript

In this tutorial we will learn about JavaScript logical operators.

We use the logical operator to compare two conditional statement to see if they satisfy the condition to execute a piece of code.

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 logical operators.

OperatorSymbolExample
Logical AND&&x && y
This will return true if value of both x and y is true.
Logical OR||x || y
This will return true if value of either x or y is true.
Logical NOT!!x
This will return true if value of x is false.

Note: x and y can be a variable or a conditional statements.

Click here for AND, OR and NOT logical gate tutorial.

Logical AND

In the following example we are checking whether variable x and y both are true.

var x = true;
var y = true;

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

In the following example we are checking whether the two conditional statements are true.

var x = 10;
var y = -20;

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

In the above code, (x > 0) is true because x is 10 and is greater than 0.

And (y < 0) is true because y is -20 and is less than 0.

Both the conditional statements are true so, the final result is also true.

Logical OR

In the following example we are checking whether variable x or y is true.

var x = true;
var y = false;

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

In the above code, (x || y) is true because x is true. And to get true result we need only one side to be true.

var x = false;
var y = false;

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

In the above code, (x || y) is false because both x and y are false.

Logical NOT

This operator works with one variable or conditional statement and inverts its value.

In the following example we are checking whether variable x is true.

var x = true;

console.log(!x);	//this will print false proving that x is true

In the above code, (!x) is false because x is true. And logical NOT inverts true to false.

var x = 10;
var y = 20;

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

In the above code, (x > y) is false because x is 10 and y is 20 so, x is less than y. And logical NOT of false value is true hence the result is true.