Skip to main content

Boolean Data Type in TypeScript

Boolean Data Type in TypeScript

The boolean data type in TypeScript represents a logical entity that can have one of two values: true or false. This type is used for conditions, flags, and binary state representation.


Basic Usage

The boolean type is used to represent truth values. It is commonly used in conditional statements and expressions. Here’s a basic example:


let isActive: boolean = true;
let hasPermission: boolean = false;
console.log(isActive, hasPermission); // Output: true false

Boolean Functions and Methods

While boolean values themselves do not have methods, they are often used in conjunction with conditional logic and expressions. Below is a table that outlines common functions and operations involving boolean values:

Function/Method Description
Boolean(value) Converts a value to a boolean. Returns true for truthy values and false for falsy values.
!value Negates the boolean value. If value is true, it becomes false and vice versa.
&& (logical AND) Logical AND operator. Returns true if both operands are true, otherwise returns false.
|| (logical OR) Logical OR operator. Returns true if at least one operand is true, otherwise returns false.
^ (logical XOR) Logical XOR operator. Returns true if exactly one operand is true, otherwise returns false.

Examples of Boolean Functions and Methods

Boolean(value)

The Boolean(value) function converts a value to its boolean representation:


console.log(Boolean(1)); // Output: true
console.log(Boolean(0)); // Output: false
console.log(Boolean("hello")); // Output: true
console.log(Boolean("")); // Output: false

Negation with !

The !value operation negates a boolean value:


let isActive: boolean = true;
console.log(!isActive); // Output: false

let isCompleted: boolean = false;
console.log(!isCompleted); // Output: true

Logical AND (&&)

The && operator performs a logical AND operation:


let hasPermission: boolean = true;
let isAdmin: boolean = false;

console.log(hasPermission && isAdmin); // Output: false
console.log(hasPermission && !isAdmin); // Output: true

Logical OR (||)

The || operator performs a logical OR operation:


let hasPermission: boolean = true;
let isAdmin: boolean = false;

console.log(hasPermission || isAdmin); // Output: true
console.log(!hasPermission || isAdmin); // Output: false

Logical XOR (^)**

The ^ operator performs a logical XOR operation:


let condition1: boolean = true;
let condition2: boolean = false;

console.log(condition1 ^ condition2); // Output: true
console.log(condition1 ^ !condition2); // Output: false

Conclusion

The boolean type in TypeScript is fundamental for controlling flow and making decisions in your code. By understanding and using boolean operations effectively, you can manage conditions and control logic in a clear and concise manner.

Comments