JavaScript boolean type

Created with Sketch.

JavaScript boolean type

Summary: in this tutorial, you’ll learn about the JavaScript boolean type that has two literal values true and false.

Introduction to the JavaScript boolean type

The JavaScript boolean primitive type has two literal values: true and false.

The following example declares two variables and initializes their values to true and false:

let completed = true;
let running = false;

Code language: JavaScript (javascript)

The boolean’s literal values are case-sensitive. This means that the True and False are valid identifiers but they’re not boolean values.

JavaScript allows the values of other types to be cast to boolean values. To cast a non-Boolean value to a boolean value, you use the built-in Boolean() function. For example:

let error = 'An error occurred';
let hasError = Boolean(error);

console.log(hasError);

Code language: JavaScript (javascript)

Output:

true

Code language: JavaScript (javascript)

How it works.

  • First, declare a variable error that holds a literal string 'An error occurred'.
  • Second, cast the error variable to a boolean value using the Boolean() function.
  • Third, output the value of the hasError variable to the console.

Because the error variable holds a non-empty string, the Boolean() function casts its value to true.

The following table shows how the Boolean() function casts the values of other types to boolean values:

Data TypeValues converted to trueValue Converted to false
stringAny non-empty string“” (empty string)
numberAny Non-zero number0, NaN
objectAny objectnull
undefined(not relevant)undefined

This table is important because some statements automatically cast a non-boolean value to a boolean value using the Boolean() function.

For example, the if statement executes a block if a condition is true. If you use a non-boolean value, it’ll use the Boolean() function to implicitly cast that value to a boolean value.

Note that you’ll learn about the if statement in the if tutorial.

See the following example:

let error = 'An error occurred';

if (error) {
console.log(error);
}

Code language: JavaScript (javascript)

Output:

An error occurred

 

In this example, since the error variable holds a non-empty string, the if statement evaluates its value to true. Therefore, it executes the console.log(error) to output the error to the console.

If you change the value of the error variable to an empty string (""), you won’t see anything in the output because the if statement evaluates it as false:

let error = '';
if (error) {
console.log(error);
}

Code language: JavaScript (javascript)

Summary

  • JavaScript boolean type has two literal values true and false.
  • Use the Boolean() function to cast a non-boolean values to a boolean value.
  • Some statements implicitly cast a non-boolean value into a boolean value.

Leave a Reply

Your email address will not be published. Required fields are marked *