JavaScript Comparisons
Comparison operators compare two values and return a boolean. They are fundamental for decision-making, determining equality, ordering, and identity of values.
Key Topics
Equality Operators
==
checks equality with type coercion, while ===
checks equality without converting types.
console.log(5 == "5");
console.log(5 === "5");
Output
> true
> false
Explanation: ==
considers "5" equal to 5 due to type coercion, while ===
checks type as well, returning false.
Relational Operators
Operators like >
, <
, >=
, and <=
compare relative ordering of values.
console.log(10 > 5);
console.log(2 <= 2);
Output
> true
> true
Explanation: 10 is greater than 5, and 2 is less than or equal to 2, both are true comparisons.
Strict Equality
===
(strict equality) ensures that both type and value must match for true.
console.log(true === 1);
console.log(false === 0);
Output
> false
> false
Explanation: Even though 1
is often truthy, true === 1
is false because they differ in type. The same applies to false === 0
.
JavaScript Usage in DOM
Comparisons help you show or hide elements, change styles, or control behavior based on conditions in the browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Comparisons in DOM</title>
</head>
<body>
<h1>Comparison Demo</h1>
<input type="number" id="numInput" placeholder="Enter a number">
<button onclick="checkNumber()">Check</button>
<p id="result"></p>
<script>
function checkNumber() {
let val = parseInt(document.getElementById("numInput").value);
if (val > 10) {
document.getElementById("result").textContent = "Greater than 10";
} else {
document.getElementById("result").textContent = "10 or less";
}
}
</script>
</body>
</html>
Key Takeaways
- Equality:
==
allows type coercion,===
enforces strict equality. - Relational Operators: Compare sizes and ordering of values.
- Strict Equality: Ensures both type and value match.
- DOM Integration: Control UI based on comparison results.