Javascript Boolean Type

Introduction

Javascript Boolean type has only two literal values: true and false.

These values are distinct from numeric values.

true is not equal to 1, and false is not equal to 0.

Assignment of Boolean values to variables is as follows:

let found = true; 
let lost = false; 

All types of values have boolean equivalents in Javascript.

To convert a value into its Boolean equivalent, call Boolean() casting function:

let text = "Hello world!"; 
let textAsBoolean = Boolean(text); 

In this example, the string text is converted into a boolean value.

The value is stored in textAsBoolean.

The Boolean() casting function can be called on any type of data and will always return a Boolean value.

The following table outlines the various data types and their specific conversions.

Data TypeValues Converted To True Values Converted To False
Boolean true false
String Any nonempty string"" (empty string)
Number Any nonzero number including infinity 0, NaN
Object Any objectnull
Undefinedn/a undefined

Java flow-control statements, such as the if statement, automatically perform this Boolean conversion:

let text = "Hello world!"; 
if (text) { //from www  . j a  va  2  s. co m
   console.log("Value is true"); 
} 

In this example, the console.log will be displayed because the string text is automatically converted into its Boolean equivalent (true).




PreviousNext

Related