JavaScript Booleans

About JavaScript Booleans

In JavaScript, booleans represent logical value: true and false.

Booleans are often used in conditional testing and are fundamental to control flow within the language.

Booleans can be created directly using the true or false keywords.

Booleans play a vital role in making decisions within code.

Booleans Declaration

Booleans can be declared/created by assigning a boolean value true or false to a variable as demonstrated in the following examples:

Output of the above example
true
false 
                                                        
Explanation of the code
  • let isTrue = true;: This line declares a variable named 'isTrue' and assigns the boolean value true. Thus a boolean is created.
  • let isFalse = false;: This line declares a variable named 'isFalse' and assigns the boolean false. Thus another boolean is created.
  • console.log(isTrue);: In the line, 'console.log()' method prints the boolean value of 'isTrue' variable in the web console.
  • console.log(isFalse);: In the line, 'console.log()' method prints the boolean value of 'isFalse' variable in the web console.

JS Boolean Constructor

The JavaScript 'Boolean()' constructor can be used to convert other data types to booleans as demonstrated in the following examples:


Truthy values: Values that return true while converting to boolean using Boolean() constructor

  • true
  • Non-zero numbers (1, 2)
  • Non-empty strings ("Hello")
  • Arrays
  • Objects


Falsy values: Values that return false while converting to boolean using Boolean() constructor

  • false
  • Number zero (0)
  • empty string ("")
  • NaN
  • null
  • undefined


Logical double NOT: Logical double NOT ( !! ) operator is often used as a shorthand for Boolean conversion as demostrated in the following examples:

Booleans Producing Operators

Boolean values are typically produced by comparison operators ( <, >, <=, >= ), equality operators ( ==, ===, !=, !== ) and logical NOT ( ! ). These operators return Boolean values (true or false) based on comparisons as demonstrated in the following examples:


Logical operators (&& and ||) are often used to combine multiple Boolean expressions. && (AND) returns true if both expressions are true. || (OR) returns true if at least one expression is true.

Use Cases of Booleans

Booleans are commonly used in condition statements like if statements, loops, and ternary operators to make decisions in code.

Booleans are also used with ternary operator which is a shorthand for if-else and is often used for quick decisions:

JavaScript Compiler For Live Practice

Practice the above JavaScript code in the following JavaScript Compiler. Create more JavaScript Booleans in the following editor and click Execute button to check the output. The output will be displayed in JavaScript Code Output section.

JavaScript logo JavaScript Compiler
JavaScript Code Output