JavaScript Comparison Operators
JavaScript comparison operators are used to compare values and return a Boolean (true
or false
). They are essential for decision-making in JavaScript, helping to control the flow of programs by evaluating conditions.
Working of Comparison Operators
1. == (Equal To)
The ==
operator checks if two values are equal. It does not check the type, meaning it will convert data types to match if necessary.
Example:
javascript
1console.log(5 == "5"); // Output: true
Explanation: Although one is a number and the other is a string, ==
considers them equal because their values are the same after type conversion.
2. === (Strict Equal To)
The ===
operator checks if two values are equal and of the same type. It ensures no type conversion happens.
Example:
javascript
1console.log(5 === "5"); // Output: false
Explanation: Here, 5
(number) is not strictly equal to "5"
(string), so the result is false
.
3. != (Not Equal)
The !=
operator checks if two values are not equal. Like ==
, it does not consider the type.
Example:
javascript
1console.log(5 != "5"); // Output: false
Explanation: The values are the same after type conversion, so !=
returns false
.
4. !== (Strict Not Equal)
The !==
operator checks if two values are not equal or if their types are different.
Example:
javascript
1console.log(5 !== "5"); // Output: true
Explanation: Since 5
(number) and "5"
(string) are of different types, !==
returns true
.
5. > (Greater Than)
The >
operator checks if the value on the left is greater than the value on the right.
Example:
javascript
1console.log(10 > 5); // Output: true
Explanation: 10
is greater than 5
, so the result is true
.
6. < (Less Than)
The <
operator checks if the value on the left is less than the value on the right.
Example:
javascript
1console.log(3 < 7); // Output: true
Explanation: 3
is less than 7
, so the result is true
.
7. >= (Greater Than or Equal To)
The >=
operator checks if the value on the left is greater than or equal to the value on the right.
Example:
javascript
1console.log(8 >= 8); // Output: true
Explanation: 8
is equal to 8
, so >=
returns true
.
8. <= (Less Than or Equal To)
The <=
operator checks if the value on the left is less than or equal to the value on the right.
Example:
javascript
1console.log(4 <= 9); // Output: true
Explanation: 4
is less than 9
, so the result is true
.
9. ? (Ternary Operator)
The ?
operator, also known as the ternary operator, is a shorthand for the if...else
statement. It allows you to execute one of two expressions based on a condition.
Syntax:
javascript
1condition ? expressionIfTrue : expressionIfFalse;
Note: We will discuss if...else
statement in upcoming lessons.
Example:
javascript
1let age = 20;
2let status = (age >= 18) ? "Adult" : "Minor";
3console.log(status); // Output: Adult
Explanation: Since age
is 20
, which is greater than or equal to 18
, the ternary operator returns "Adult"
.