Comparison operators in JavaScript are used to compare two values and return a boolean result (true or false). They are essential for making decisions in your code.
1. Equality (==)
The equality operator checks if two values are equal, performing type coercion if necessary.
Syntax
value1 == value2;
Example
console.log(5 == '5'); // Output: true
In this example, 5 (number) is compared to '5' (string). Due to type coercion, they are considered equal.
2. Strict Equality (===)
The strict equality operator checks if two values are equal and of the same type, without performing type coercion.
Syntax
value1 === value2;
Example
console.log(5 === '5'); // Output: false
Here, 5 (number) is not strictly equal to '5' (string) because their types are different.
3. Inequality (!=)
The inequality operator checks if two values are not equal, performing type coercion if necessary.
Syntax
value1 != value2;
Example
console.log(5 != '5'); // Output: false
In this case, 5 and '5' are considered equal due to type coercion, so the result is false.
4. Strict Inequality (!==)
The strict inequality operator checks if two values are not equal or not of the same type, without performing type coercion.
Syntax
value1 !== value2;
Example
console.log(5 !== '5'); // Output: true
Here, 5 (number) is strictly not equal to '5' (string) because their types differ.
5. Greater Than (>)
The greater than operator checks if one value is greater than another.
Syntax
value1 > value2;
Example
console.log(10 > 5); // Output: true
In this example, 10 is greater than 5, so the result is true.
6. Greater Than or Equal To (>=)
The greater than or equal to operator checks if one value is greater than or equal to another.
Syntax
value1 >= value2;
Example
console.log(10 >= 10); // Output: true
Here, 10 is equal to 10, so the result is true.
7. Less Than (<)
The less than operator checks if one value is less than another.
Syntax
value1 < value2;
Example
console.log(5 < 10); // Output: true
In this case, 5 is less than 10, so the result is true.
8. Less Than or Equal To (<=)
The less than or equal to operator checks if one value is less than or equal to another.
Syntax
value1 <= value2;
Example
console.log(5 <= 5); // Output: true
Here, 5 is equal to 5, so the result is true.
These operators are fundamental for making comparisons and decisions in JavaScript.
Find the below application.
comparisonOperators.js
console.log(`5 == '5' : ${5 == '5'}`); console.log(`5 == 5 : ${5 == 5}`); console.log(`5 === '5' : ${5 === '5'}`); console.log(`5 != '5' : ${5 != '5'}`); console.log(`5 != 5 : ${5 != 5}`); console.log(`5 !== '5' : ${5 !== '5'}`); console.log(`10 > 5 : ${10 > 5}`); console.log(`10 >= 10 : ${10 >= 10}`); console.log(`5 < 10 : ${5 < 10}`); console.log(`5 <= 5 : ${5 <= 5}`);
Output
5 == '5' : true 5 == 5 : true 5 === '5' : false 5 != '5' : false 5 != 5 : false 5 !== '5' : true 10 > 5 : true 10 >= 10 : true 5 < 10 : true 5 <= 5 : true
Previous Next Home
No comments:
Post a Comment