TOC
Data types:

Booleans

One of the simplest type you'll find in JavaScript, as well as in many other programming languages, is the boolean type. It can only contain two values: true or false. These two values are also keywords, meaning that you can use them directly, e.g. when assigning a value to a variable:

let b1 = false, b2 = true;
alert(b1);
alert(b2);

You will also see that a boolean value can be returned from a lot of the built-in functions of JavaScript, but also the result of using the various operators (more on those later). For instance, if you compare two numbers in various ways, you can get a boolean value back:

let n1 = 10, n2 = 20, n3 = 10;

let n1IsBiggerThanN2 = (n1 > n2);
alert(n1IsBiggerThanN2);

let n1IsSameAsN3 = (n1 == n3);
alert(n1IsSameAsN3);

That is also why you can use a condition in an if statement - it checks the condition and if it evaluates to true, the following code can be reached:

let n1 = 10, n2 = 20;

if(n2 > n1)
	alert("Go on...");

boolean vs. Boolean

The boolean type is a so-called primitive type in JavaScript, which basically just means that it's an integral and basic part of the language, which can't be extended. However, for most primitive types, JavaScript also offers an object with the same name, but starting with an UPPERCASE character. So, we have a boolean (the primitive type) and a Boolean (the corresponding object).

Usually, the object version offers you help in dealing with the underlying simple type, while allowing you to even extend this functionality. However, since boolean is SO basic (remember, it only understands the values true or false), the Boolean object is not used very frequently.

You can initiate a new Boolean object like this:

let b1 = Boolean(true);
alert(b1);

Here we create a Boolean object with the initial value "true". If we want false, we can simply change this value, or completely leave it out - an empty value is considered false as well:

let b2 = Boolean();
alert(b2);

As a little curiosity, both of these variables will be true:

let b1 = Boolean("false");
alert(b1);

let b2 = Boolean("true");
alert(b2);

Why? Because any non-empty value will be considered true.

Summary

A JavaScript boolean is a primitive type, with only two possible values: true or false. JavaScript also offers a Boolean object, but it's not commonly used.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!