Boolean Data Types in JavaScript

JavaScript2 min read
Boolean Data Types in JavaScript
javascriptboolean data typedata types

A Boolean represents a logical entity that can have only two values: true or false.

The third type of primitive data in JavaScript is the Boolean type.

1. Boolean Type

A Boolean represents a logical entity that can have only two values: true or false. Booleans are primarily used for decision-making in conditional statements.

Example: Declaring a Boolean Value

let status = true; // Print the Boolean value document.write(status); // Output: true

Explanation:

  • Here, status is a Boolean variable holding the value true.

2. Comparison Operators

  • In JavaScript, comparison operators evaluate expressions and return a Boolean value (true or false). These operators compare two values and produce a Boolean result.
  • Example: Using Comparison Operators
document.write(5 > 3); // Output: true document.write(5 < 3); // Output: false document.write(5 == 5); // Output: true document.write(5 != 3); // Output: true

Explanation:

  • The comparison operators such as >, <, ==, and != compare values and return either true or false depending on the result.

3. Logical Operators

  • JavaScript also provides logical operators to combine or manipulate Boolean values. The most commonly used logical operators are AND (&&), OR (||), and NOT (!).
  • Example: Using Logical Operators
// AND (&&) operator: both conditions must be true let andResult = (true && true); document.write(andResult); // Output: true // OR (||) operator: one of the conditions must be true let orResult = (true || false); document.write(orResult); // Output: true // NOT (!) operator: reverses the Boolean value let notResult = !true; document.write(notResult); // Output: false

Explanation:

  • AND (&&): Returns true if both operands are true. Otherwise, it returns false.
  • OR (||): Returns true if at least one operand is true. Otherwise, it returns false.
  • NOT (!): Returns the opposite of the operand's value. If the operand is true, it returns false, and vice versa.

Summary:

  • Boolean values represent true or false.
  • Comparison operators return Boolean values after evaluating expressions.
  • Logical operators like AND, OR, and NOT are used to manipulate Boolean values and combine conditions.