Importance of Booleans in JavaScript (with examples)

A JavaScript Boolean represents one of two values: true or false. Boolean values are generally the result of comparisons you make in your JavaScript programs.


This code tests to see whether the value of the variable a is equal to the number 4. If it is, the result of this comparison is the boolean value true. If a is not equal to 4, the result of the comparison is false.

If the value is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.  Everything except this value is considered as a true value.

Boolean values can also be useful for comparison. It returns true or false values.

let a=5 , b=10;
let result=a>b;

console.log(result);    //Output : false

let result1=a<b;

console.log(result1);   //Output : true        
 Boolean() Function - we can also use the boolean function to find out whether it is true or not.
let x = null;

console.log(Boolean(x));      //Output : false

We can also use logical OR and And operators with boolean values.

const a = 'abc';
const b = false;
const c = true;
const d = 0
const e = 6
const f = 9
const g = null

console.log(a || b);     // Output :"abc"
console.log(c || a);     // Output :true
console.log(b || a);     //  Output :"abc"
console.log(e || f);     //  Output : 6
console.log(f || e);     //  Output :9
console.log(d || g);     //  Output :null
console.log(g || d);     //  Output :true
console.log(a && c);     //  Output :"abc"        

As you can see, the or operator checks the first operand. If this is true it returns it immediately If it is not true it returns the second operand.

Posted in

Ankit Patel

Leave a Comment

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

Scroll to Top