Javascript Boolean Type valid representations of the false and true values

Introduction

There are only two Boolean values: true and false.

However, many different types such as numbers, strings, null, and undefined can be coerced to Boolean.

if statements, switch statements, for statements, and while statements all coerce their given values to Booleans.

// If statements internally convert the given condition or value into Boolean values. 
if (0) { // w w  w . j a  v  a 2  s.  c o  m
    console.log( "0 is true"); 
} else { 
         console.log("0 is false"); 
} 

if (-0) { 
    console.log( "-0 is true" ); 
} else { 
         console.log("-0 is false"); 
} 

if (null) { 
    console.log( "null is true" ); 
} else { 
         console.log("null is false"); 
} 

if (false) { 
    console.log( "false is true" ); 
} else { 
         console.log("false is false"); 
} 

if (NaN) { 
    console.log( "NaN is true" ); 
} else { 
         console.log("NaN is false"); 
} 

if (undefined) { 
    console.log( "undefined is true" ); 
} else { 
         console.log("undefined is false"); 
} 
if ("") { 
    console.log( "Empty String is true" ); 
} else { 
         console.log("Empty String is false"); 
} 
// Variable b holds the outcome of the comparison 
// between Variable 'a' and the number 1. 
let a = 1; 
b = (a === 1);   // true 
if ( b ) { 
    console.log("Variable b is true"); 
} else { 
    console.log("Variable b is false"); 
} 

// Examples of conditional or comparative expressions 
let c = 1 + 2; 
let d = null; 
let e = a - 3; 
let f = undefined; 

if (c) { 
         console.log("Variable c is true"); 
} else { 
         console.log("Variable c is false"); 
} 

if (d) { 
         console.log("Variable d is true"); 
} else { 
         console.log("Variable d is false"); 
} 

if (e) { 
         console.log("Variable e is true"); 
} else { 
         console.log("Variable e is false"); 
} 

if (f) { 
         console.log("Variable f is true"); 
} else { 
         console.log("Variable f is false"); 
} 



PreviousNext

Related