Overview
JavaScript has a convention of Truthy and Falsey (sometimes referred to as Falsy).
When JavaScript is dealing with booleans it automatically converts non boolean datatype values to boolean. This is known as type coercion.
Falsey values are datatype values that get converted to false. They are
false (boolean)
0 (number)
-0 (number)
0n (BigInt)
-0n (BigInt)
"" (string)
null
undefined
NaN and
document.all
Truthy values are datatype values that get converted to true. They are any value that is not listed above as a falsey value.
There are 8 datatypes in JavaScript, and we will go through truthy and falsey examples of each.
Number
String
Boolean
Null
Undefined
BigInt
Symbol
Object
Number
Any number is true except 0 and -0.

String
All strings are true, except empty strings, even "false" in a string is true.

Boolean
Simple to remember this one true is true and false is false.

Nulls
Null is always false.

Undefined
Undefined is always false.

NaN
When passing a string instead of number a NaN datatype is returned. NaN datatypes are always false

BigInt
All BigInt's are true except -0n and 0n.
Symbols
Symbols are always true
Objects
Objects are always true, even empty objects.
Document.All
Documnet.All is always false
Arrays
Arrays are always true.
Comparing Truthy and Falsey values
PLEASE NOTE it is bad practice to not use the strict equality operator, always use ===, the below code is for demonstration purposes only. Stange behavior occurs when using loose equality operator, ==. Many people make the mistake of thinking this is related to truthy and falsey values HOWEVER its due to the complex rules around datatype conversion.
For example
1==true will returns true,
12==true returns false
1==true returns true because the JavaScript conversion rules converts a number of 1 to a boolean of true. It is easy to think this is because 1 is a truthy value.
BUT 12==true returns false because number 12 does not convert to a true boolean value. Therefore, clearly the equality operator does not care about truthy or falsey values.
Commenti