JavaScript Comparisons
JavaScript provides various operators to compare values. These comparison operators return Boolean values (`true` or `false`) based on whether the comparison is true or not.
1. Comparison Operators
Here are the primary comparison operators in JavaScript:
- Equal to (`==`)
Checks if two values are equal, with type conversion if necessary:
// Equal to operator
console.log(5 == 5); // true
console.log(5 == '5'); // true (type coercion)
console.log(5 == 10); // false
- Strict Equal to (`===`)
Checks if two values are equal and of the same type, without type conversion:
// Strict equal to operator
console.log(5 === 5); // true
console.log(5 === '5'); // false (different types)
console.log(5 === 10); // false
- Not Equal to (`!=`)
Checks if two values are not equal, with type conversion if necessary:
// Not equal to operator
console.log(5 != 10); // true
console.log(5 != '5'); // false (type coercion)
console.log(5 != 5); // false
- Strict Not Equal to (`!==`)
Checks if two values are not equal and/or not of the same type, without type conversion:
// Strict not equal to operator
console.log(5 !== 10); // true
console.log(5 !== '5'); // true (different types)
console.log(5 !== 5); // false
- Greater Than (`>`) and Less Than (`<`)< /h3>
Checks if one value is greater than or less than another value:
// Greater than and less than operators
console.log(10 > 5); // true
console.log(5 < 10); // true
console.log(10 > 10); // false
console.log(10 < 5); // false
- Greater Than or Equal to (`>=`) and Less Than or Equal to (`<=`)< /h3>
Checks if one value is greater than or equal to, or less than or equal to another value:
// Greater than or equal to and less than or equal to operators
console.log(10 >= 10); // true
console.log(5 <= 10); // true
console.log(10 >= 5); // true
console.log(10 <= 5); // false
2. Comparison with Type Conversion
JavaScript performs type conversion in some comparisons. Be cautious when using the `==` operator as it can lead to unexpected results:
// Type conversion example
console.log('5' == 5); // true (string '5' is converted to number 5)
console.log('5' === 5); // false (different types)
console.log(0 == false); // true (0 is converted to false)
console.log(0 === false); // false (different types)
3. Comparing Objects
When comparing objects, JavaScript compares references, not the actual contents of the objects:
// Comparing objects
const obj1 = { name: 'John' };
const obj2 = { name: 'John' };
const obj3 = obj1;
console.log(obj1 == obj2); // false (different references)
console.log(obj1 === obj2); // false (different references)
console.log(obj1 == obj3); // true (same reference)
console.log(obj1 === obj3); // true (same reference)
4. Best Practices
Use the strict equality (`===`) and strict inequality (`!==`) operators to avoid unexpected results caused by type conversion. Always be aware of how JavaScript handles type coercion in comparisons.