javascript Tutorial

JavaScript Boolean

Learn more about one of the world’s most popular programming languages.

Logical information in JavaScript is represented by a data type called boolean. They are very useful while writing conditional statements or while making logical decisions in code. They store one of the two values in it – true or false.

Code Example
const hasGraduated = true;
const isRaining = false;
const result = 75 > 85;
 
console.log(hasGraduated); // prints true
console.log(isRaining); // prints false
console.log(result); // prints false
 
console.log(typeof hasGraduated); // prints boolean
console.log(typeof isRaining); // prints boolean
console.log(typeof result); // prints boolean

JavaScript Boolean Value

In JavaScript a boolean value can be represented with the primitive “boolean” data type.

Code Example
const sunnyDay = true;
console.log(typeof sunnyDay);  // boolean 
console.log(sunnyDay === true); // true

Boolean values can also be represented with instances of the Boolean object. The JavaScript Boolean object is an object wrapper for a boolean value. The value passed as the first argument to the constructor will be converted to  a boolean value. The value will be false if the provided argument is 0, -0, null, false, NaN, undefined, or the empty string, or if the value is omitted. Any other value will create an instance with an internal value of true. It is important, however, not to confuse the instances of the Boolean object with the primitive value true or false.

Code Example
const sunnyDay = new Boolean(‘something’); 
console.log(typeof sunnyDay);  // object 
console.log(sunnyDay === true); // false
console.log(typeof sunnyDay.valueOf());  // boolean
console.log(sunnyDay.valueOf() === true); // true
 
const sunnyDay = new Boolean(); 
console.log(typeof sunnyDay);  // object 
console.log(sunnyDay === true); // false
console.log(typeof sunnyDay.valueOf());  // boolean
console.log(sunnyDay.valueOf() === false); // true

JavaScript Boolean Function

JavaScript uses the Boolean function to convert other types to a primitive boolean type. It is important to note that when used with the new keyword in front of it, the Boolean function acts as a constructor and will return an instance of the Boolean object. You must use the valueOf method to access the underlying primitive value. If the new keyword is omitted, then the function will return a primitive boolean value directly.

Code Example
const sunnyDay = Boolean(1);
console.log(typeof sunnyDay); // boolean
console.log(sunnyDay); // true
 
const rainyDay = new Boolean(1);
console.log(typeof rainyDay); // object
console.log(typeof rainyDay.valueOf()); // boolean
console.log(rainyDay.valueOf()); // true

Learn JavaScript Today

Get hands-on experience writing code with interactive tutorials in our free online learning platform.

  • Free and fun
  • Designed for beginners
  • No downloads or setup required