JavaScript: 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.

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

Values in Boolean Context

When a value is evaluated in boolean context, such as in a if statement, the function Boolean is called on the value, and returns true or false

 if ( 3 ) {console.log( "y" ); } else {console.log( "n" );} // y 

False are:

// all of the following prints 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) );

Everything else is true.

// all of the following prints 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

Logic Operators

x && y
and” operator. Return true if both Boolean(x) and Boolean(y) are true, else false. If Boolean(x) is false, y is not evaluated.
x || y
or” operator. Return true if one of Boolean(x) or Boolean(y) is true, else return false. If Boolean(x) is true, y is not evaluated.
!x
not” operator. Reverse the boolean value. Return true if Boolean(x) is false, return false if Boolean(x) is true.
// “and” operator
console.log( true && true );
// true

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

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

Greater Than, Less Than

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 「===」

// all true

Difference between == and ===

Equality

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc