Boolean in JavaScript

·

2 min read

What are Booleans?

  1. Data Type: Booleans are a basic data type in JavaScript.

  2. Two values: Values can be only true or false.

  3. 'true' is a string, not a boolean.

  4. for eg.

console.log(5<9);

The output would be true because we know that 5 is less than 9 so it returns true as a output.

now if we use typeof() operator, it will give the type of our expression which is boolean.

Note: If you wrap true or false in a quote, then they are considered as a string.

For example,

const a = 'true';
console.log(typeof a); // string

JavaScript Boolean Methods

Here is a list of built-in boolean methods in JavaScript.

MethodDescription
toString()returns a boolean value by converting boolean to a string
valueOf()returns the primitive value of a boolean

Example: Using toString()

let count = false;

// converting to string
let result = count.toString();

console.log(result);
console.log(typeof result);

Output

false
string

Example: Using valueOf()

let count = true;

// converting to string
let result = count.valueOf();

console.log(result);

console.log(typeof result);

Output

true
boolean

In JavaScript, undefined, null, 0, NaN, '' converts to false. For example,

let result;
// empty string
result = Boolean('');
console.log(result); // false

result = Boolean(0);
console.log(result); // false

result = Boolean(undefined);
console.log(result); // false

result = Boolean(null);
console.log(result); // false

result = Boolean(NaN);
console.log(result); // false