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: Value 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. JavaScript Basics
  2. Value Types
  3. true, false
  4. Operators
  5. Variable
  6. if then else
  7. for while do Loop
  8. Array Basics
  9. Object Basics
  10. RegExp Tutorial

Boolean Topic

  1. JS: true, false
  2. JS: Boolean Object
  3. JS: Boolean.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc