Typescript Boolean

The boolean is a primitive type in Typescript. It represents a simple true/false value. They are implemented as numerical values with a single binary digit (i.e., 0 & 1). The Boolean is an object wrapper for a boolean value. Also, let us find the difference between Boolean vs boolean. We also learn how to convert boolean to string and string to boolean.

Defining Boolean

There are two ways you can create the primitive boolean variable. using the normal variable declaration or using the global Boolean function.

boolean declaration

The following example creates two primitive boolean variables. You can see that the typeof returns as boolean.

Example

Boolean Global function

The zero, empty string, null, undefined, NaN returns false

Everything else returns true. Including an empty object.

Boolean Object

The Boolean is an object and is a wrapper around boolean.primitive type. You can create a Boolean object using the constructor.

As shown in the previous example, zero, empty string, null, undefined results in false. Everything else returns true.

You can use the valueOf method to get the primitive boolean back.

Boolean vs boolean

The boolean is a primitive type & Boolean is an object.

The boolean is created using variable declaration or using the Boolean function. The Boolean object is created using the constructor (using the new Boolean())

And since the Boolean object is an object, comparing it with boolean value always results in true, irrespective of its internal value.

Convert boolean to number

Converting the boolean to the number primitive will result in 1 for true and 0 for false.

Convert boolean to string

Summary

The boolean is a primitive type in Typescript. The Typescript also has the Boolean object. Always use the primitive boolean. When converting the other data types to boolean remember that zero, empty string, null, undefined, NaN returns false. Everything else returns true.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top