JavaScript Boolean
Subject: JavaScript
In JavaScript, a Boolean represents one of two values: true or false. It is commonly used in conditional statements, comparisons, and logical operations to control program flow.
What is a Boolean?
A Boolean is a primitive data type that can only be:
- true
- false
It is often the result of comparisons, logical evaluations, or used explicitly to represent a binary state (e.g., on/off, yes/no, active/inactive).
Creating Boolean Values
- Using Boolean Literals:
- Using the Boolean() Constructor:
Note: Double negation !! quickly converts any value to a Boolean.
Falsy and Truthy Values
JavaScript treats some values as false in Boolean contexts:
- false
- 0
- "" (empty string)
- null
- undefined
- NaN
All other values are considered truthy, treated as true in Boolean expressions.
Boolean in Conditional Statements
Boolean with Comparison Operators
Boolean with Logical Operators
Example: Form Validation
Key Takeaways
- Boolean values represent true or false.
- You can create Booleans using literals or the Boolean() function.
- Falsy values evaluate to false; all other values are truthy.
- Booleans are essential for conditions, comparisons, and logic control in JavaScript.
- Logical operators like
&&,||, and!help manipulate Boolean logic.