JavaScript Booleans

Booleans represent logical values true or false. They are crucial for decision-making and conditional logic in JavaScript, controlling flow and behavior of code segments.

Key Topics

Boolean Values

The boolean type has only two values: true and false.

let isComplete = true;
let isPending = false;
console.log(isComplete, isPending);

Output

> true false

Explanation: Booleans are straightforward: true represents a positive condition, and false a negative one.

Type Coercion

JavaScript can convert values to booleans, with certain rules: non-empty strings are true, the number 0 is false, and so forth.

console.log(Boolean("Hello"));
console.log(Boolean(""));
console.log(Boolean(0));
console.log(Boolean(123));

Output

> true

> false

> false

> true

Explanation: Non-empty strings and non-zero numbers are true, while empty strings and zero are false.

Logical Operators

Logical operators like && (AND), || (OR), and ! (NOT) combine or invert boolean values.

console.log(true && false);
console.log(true || false);
console.log(!true);

Output

> false

> true

> false

Explanation: true && false is false, true || false is true, and !true flips true to false.

JavaScript Usage in DOM

This example uses booleans to conditionally display content on a webpage.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Booleans in DOM</title>
</head>
<body>
    <h1>Boolean Demo</h1>
    <button onclick="toggleContent()">Toggle Content</button>
    <p id="display" style="display:none;">This is a hidden message.</p>

    <script>
        let isVisible = false;
        function toggleContent() {
            isVisible = !isVisible;
            document.getElementById("display").style.display = isVisible ? "block" : "none";
        }
    </script>
</body>
</html>

Key Takeaways

  • Values: Only true or false.
  • Type Coercion: Certain values implicitly convert to booleans.
  • Logical Operators: Combine, invert, or evaluate boolean expressions.
  • DOM Integration: Use booleans to control what content to show or hide.