...

/

Logical Operators

Logical Operators

Learn how logical and comparison operators in JavaScript work to make decisions and handle conditions.

JavaScript provides logical operators to evaluate expressions and make decisions in code. These operators form the backbone of conditional logic and expression evaluation in JavaScript. Let’s start the lesson with the comparison operators, which is a special type of logical operator.

Comparison operators in JavaScript

Comparison operators allow us to compare two values and return a boolean result (true or false). These operators are essential for evaluating conditions. A summary of these operators, along with a brief description and an example, is given in the table below.

Operator

Description

Example

==

Equal to

5 == '5'

(true)

===

Strict equal to

5 === '5'

(false)

!=

Not equal to

5 != '3'

(true)

!==

Strict not equal to

5 !== '5'

(true)

<

Less than

3 < 5

(true)

<=

Less than or equal to

5 <= 5

(true)

>

Greater than

10 > 6

(true)

>=

Greater than or equal to

10 >= 10

(true)

Let’s look at some of the operators in action in the code below.

Press + to interact
let num = 5;
let str = '5';
console.log(num == str); // true (type coercion occurs)
console.log(num === str); // false (strict equality, no type coercion)

In the above code:

  • Line 3: The == operator compares values after type conversion, so 5 and '5' are considered equal.

  • Line 4: The === operator does not perform type conversion and checks for both value and type equality.

Press + to interact
let a = 3;
let b = 7;
console.log(a < b); // true (3 is less than 7)
console.log(a >= b); // false (3 is not greater than or equal to 7)

In the above code:

  • Line 3: The < operator checks if the left operand is less than the right operand.

  • Line 4: The >= operator checks if the left operand is greater than or equal to the right operand. ...