Home >Web Front-end >JS Tutorial >Truthy and Falsy Values: When All is Not Equal in JavaScript
JavaScript's equality comparisons can be tricky due to its loose typing. This article explores the nuances of double (==) and triple (===) equals operators, and the concept of truthy and falsy values.
Understanding these concepts leads to cleaner, more predictable code.
Key Takeaways:
false
, 0
, -0
, 0n
, ""
, null
, undefined
, and NaN
. All other values are truthy, including '0'
, 'false'
, []
, {}
, and functions.false == 0 == ''
is true, but [] == true
is false, and [] == false
is true! Strict equality avoids these ambiguities.===
) and explicitly convert to Boolean values (Boolean()
or !!
) when necessary. This ensures predictable behavior.JavaScript's Typing System:
JavaScript variables are loosely typed:
<code class="language-javascript">let x; x = 1; // x is a number x = '1'; // x is a string x = [1]; // x is an array</code>
Loose equality (==) converts values to strings before comparison:
<code class="language-javascript">// all true 1 == '1'; 1 == [1]; '1' == [1];</code>
Strict equality (===) considers type:
<code class="language-javascript">// all false 1 === '1'; 1 === [1]; '1' === [1];</code>
JavaScript's primitive types are: undefined
, null
, boolean
, number
, bigint
, string
, and symbol
. Everything else is an object (including arrays).
Truthy vs. Falsy Values:
Each value has a Boolean equivalent:
false
, 0
, -0
, 0n
, ""
, null
, undefined
, NaN
Example:
<code class="language-javascript">if (value) { // value is truthy } else { // value is falsy }</code>
document.all
(deprecated) is also falsy.
Loose Equality (==) Comparisons:
Loose equality leads to unexpected results with truthy/falsy values:
Strict Equality (===) Comparisons:
Strict equality provides clearer results:
Note that NaN === NaN
is always false
.
Recommendations:
!x
instead of x == false
.===
): Provides more predictable results.Boolean(x)
or !!x
for explicit Boolean conversion.Conclusion:
Understanding truthy/falsy values and using strict equality improves code reliability. Avoid the pitfalls of loose comparisons to prevent debugging headaches.
FAQs (abbreviated for brevity):
Boolean()
function.==
vs ===
: Loose vs. strict equality; ===
avoids type coercion.&&
) and OR (||
).0
, ""
, null
, undefined
, NaN
, -0
.Boolean()
.0
vs '0'
, empty arrays/objects are truthy.The above is the detailed content of Truthy and Falsy Values: When All is Not Equal in JavaScript. For more information, please follow other related articles on the PHP Chinese website!