JS: true, false

By Xah Lee. Date: . Last updated: .

true and false are builtin primitive values.

Type of true and false is "boolean", and they are the only possible values of boolean type.

〔►see JS: Data Types

console.log ( (typeof true) === "boolean" ); // true
console.log ( (typeof false) === "boolean" ); // true

False are:

Everything else eval to true.

// all of the following eval to false.

console.log( Boolean(0) );
console.log( Boolean(0.0) );
console.log( Boolean(0.) );
console.log( Boolean(.0) );

console.log( Boolean("") );

console.log( Boolean(null) );
console.log( Boolean(undefined) );
console.log( Boolean(NaN) );

// anything else is true

Everything else is true.

// all of the following eval to true

console.log( Boolean(1) );
console.log( Boolean(-1) );
console.log( Boolean(Infinity) );
console.log( Boolean({}) ); // empty object
console.log( Boolean([]) ); // empty array
console.log( Boolean(function () {}) ); // function object

〔►see JS: Boolean Object

Logic Operators

// “and” operator
console.log ( true && true );
// true

// “or” operator
console.log ( true || true );
// true

// “negation” operator
console.log ( !false );
// true

Comparison Operators

console.log ( 3 < 4 );
console.log ( 4 > 3 );

console.log ( 3 <= 4 );
console.log ( 3 >= 3 );

console.log ( 3 == "3" );
// note: 「==」 does automatic type conversion

console.log  ( 3 === "3" );
// false
// 「===」 does not do type conversion

console.log ( 3 != 4 );
// The 「!=」 is the negation of 「==」

console.log ( 3 !== 4 );
// The 「!==」 is the negation of 「===」

What is the difference between == and ===?

== does automatic type conversion. === does not.

You should always use === instead of ==. When testing for boolean, always be as explicit as possible. Don't rely on what the language considers as true.

Reference

ECMAScript® 2016 Language Specification#sec-toboolean

JavaScript Basics

  1. How to Run JavaScript
  2. JS: How to Use Browser Console
  3. JavaScript Tutorial by Example
  4. JS: Data Types
  5. JS: true, false
  6. JS: Operators
  7. JS: Variable
  8. JS: Branch Control: if then else, switch
  9. JS: for while do Loop
  10. JS: Array Basics
  11. JS: Object Basics
  12. JS: RegExp Tutorial
  13. JS: Throw Try Catch Finally

Boolean Topic

  1. JS: true, false
  2. JS: Boolean Object
  3. JS: Boolean.prototype
Like what you read? Buy JavaScript in Depth