Comparison Operators in JavaScript
Purpose
- Comparison operators are used to compare two values.
- They return a boolean value (either true or false) based on the comparison result.
Common Assignment Operators:
- == (Loose Equality): Checks if two values are equal, but may perform type coercion (e.g., ‘5’ == 5 will return true).
- === (Strict Equality): Checks if two values are equal in both value and type.
let x = 5;
let y = '5';
console.log(x == y); // true (loose equality)
console.log(x === y); // false (strict equality)
- != (Not Equal): Checks if two values are not equal (loose equality).
- !== (Strict Not Equal): Checks if two values are not equal in both value and type.
- > (Greater Than): Checks if the left-hand operand is greater than the right-hand operand.
- < (Less Than): Checks if the left-hand operand is less than the right-hand operand.
- >= (Greater Than or Equal To): Checks if the left-hand operand is greater than or equal to the right-hand operand.
- <= (Less Than or Equal To): Checks if the left-hand operand is less than or equal to the right-hand operand.
Example:
let a = 10;
let b = 5;
console.log(a > b); // true
console.log(a < b); // false
console.log(a >= b); // true
console.log(a <= b); // false
Key Points
- Comparison operators are essential for making decisions in your JavaScript code (e.g., in if statements and loops).
- Always use strict equality (===) when possible to avoid unexpected behavior due to type coercion.