JavaScript Comparison
In JavaScript, you can compare values using comparison operators. These operators return a Boolean value (true or false) depending on whether the comparison is true or false.
Here are the comparison operators available in JavaScript:
Operator | Description | Example |
---|---|---|
Equal (==): | Checks if two values are equal. | console.log(5 == 5); // true |
Not Equal (!=): | Checks if two values are not equal. | console.log(5 != 3); // true |
Strict Equal (===): | Checks if two values are equal without type coercion. | console.log(5 === 5); // true |
Strict Not Equal (!==): | Checks if two values are not equal without type coercion. | console.log(5 !== 3); // true |
Greater Than (>) | Checks if the left operand is greater than the right operand. | console.log(5 > 3); // true |
Less Than (<): | Checks if the left operand is less than the right operand. | console.log(5 < 7); // true |
Greater Than or Equal To (>=): | Checks if the left operand is greater than or equal to the right operand. | console.log(5 >= 3); // true |
Less Than or Equal To (<=): | Checks if the left operand is less than or equal to the right operand. | console.log(5 <= 7); // true |
Comparing Different Types
Comparing data of different types may give unexpected results.
When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison. An empty string converts to 0.
A non-numeric string converts to NaN which is always false.