Boolean in JavaScript: Yes/True or No/False

Javascript

In programming, a Boolean represents a logical entity that can either be true or false. It’s a crucial data type that forms the backbone of decision-making in code.

Boolean Values

Boolean values are the building blocks of logical operations. In JavaScript, they are expressed as true or false

yes or no, providing a binary foundation for decision-making in code.

Let’s walk through a quick example to solidify our understanding:

let isCodingFun = true;

if (isCodingFun) {
  console.log("Coding is indeed fun!");
} else {
  console.log("Coding might not be everyone's cup of tea.");
}

In this example, the variable isCodingFun is assigned the Boolean value true, triggering the execution of the first block.

JavaScript Boolean Properties

JavaScript provides inherent properties associated with Boolean objects. These include:

  • constructor: Returns the function that created the Boolean object.
  • prototype: Allows you to add properties and methods to Boolean objects.

Comparisons and Conditions

In JavaScript, you can compare values using various operators, such as ==, ===, !=, !==, <, >, <=, and >=. These operators allow you to compare two values and return a Boolean result.

For Conditions you can refer this.

JavaScript Boolean Methods

Here are some of the essential methods related to Booleans in JavaScript presented in a tabular format:

MethodDescription
toString()Converts a Boolean value to a string representation.
valueOf()Returns the primitive value of a Boolean object.
toSource()returns the source of Boolean object as a string.

1. toString()

The toString() method converts a Boolean value to its string representation.

let myBoolean = true;

// Using toString() method
let booleanString = myBoolean.toString();

console.log("Original Boolean Value: ", myBoolean);
console.log("String Representation: ", booleanString);
//Output:
//Original Boolean Value: true
//String Representation: true

In this example, the toString() method is used to convert the Boolean value true to its string representation, which is also "true".

2. valueOf()

The valueOf() method returns the primitive value of a Boolean object.

let myBoolean = new Boolean(false);

// Using valueOf() method
let booleanPrimitive = myBoolean.valueOf();

console.log("Original Boolean Object: ", myBoolean);
console.log("Primitive Value: ", booleanPrimitive);
//Output:
//Original Boolean Object: Boolean { false }
//Primitive Value: false

In this example, the valueOf() method is applied to a Boolean object created using the new Boolean() constructor. It returns the primitive value, which is false.