JavaScript Boolean Type
JavaScript Boolean Type
Donate Now
(https://www.javascripttutorial.net/donation/)
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() (https://www.javascripttutorial.net/javascript-
https://www.javascripttutorial.net/javascript-boolean-type/ 1/4
29/07/2022, 07:56 JavaScript Boolean Type
console.log(hasError);
Output:
true
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.
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:
This table is important because some statements automatically cast a non-boolean value to a boolean
value using the Boolean() function.
https://www.javascripttutorial.net/javascript-boolean-type/ 2/4
29/07/2022, 07:56 JavaScript Boolean Type
if (error) {
console.log(error);
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 :
if (error) {
console.log(error);
Summary
https://www.javascripttutorial.net/javascript-boolean-type/ 3/4
29/07/2022, 07:56 JavaScript Boolean Type
JavaScript boolean type has two literal values true and false .
https://www.javascripttutorial.net/javascript-boolean-type/ 4/4