JavaScript: What's True, False?

By Xah Lee. Date: . Last updated: .

true and false are builtin boolean values.

〔►see JavaScript: Data Types

False are:

Everything else eval to true.

// the following eval to false. Everything else is true.

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

console.log( Boolean("") );     // false

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

Everything else is true.

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

Logic Operators

true && true // ⇒  true. The “and” operator

true || true // ⇒  true. The “or” operator

!true // ⇒ false. The “negation” operator

Comparison Operators

3 < 4;         // ⇒ true
3 > 4;         // ⇒  false

3 <= 4;         // ⇒ true
3 >= 4;         // ⇒  false

3 == 3;        // ⇒ true.
3 == "3";      // ⇒ true.  note: 「==」 does automatic type conversion
3 === "3";     // ⇒ false.  True if both sides are same type and equal

3 != 4;        // ⇒ true. The 「!=」 is the negation of 「==」
3 !== 4;       // ⇒ true. 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. JavaScript: How to Use Browser's JS Console
  3. JavaScript Tutorial by Example
  4. JavaScript: Data Types
  5. JavaScript: What's True, False?
  6. JavaScript: Operators
  7. JavaScript: Variable
  8. JavaScript: Branch Control: if then else, switch
  9. JavaScript: for while do Loop
  10. JavaScript: Array Basics
  11. JavaScript: Object Basics
  12. JavaScript: RegExp Tutorial
  13. JavaScript: Throw Try Catch Finally

Boolean Topic

  1. JavaScript: What's True, False?
  2. JavaScript: Boolean() Constructor Object
  3. JavaScript: Boolean.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.