JavaScript·100 questions

QUESTION: What are truthy and falsy values?

Answer

In JavaScript, all values in the context of logical operations are divided into two categories: truthy, which evaluate to true, and falsy, which evaluate to false. Understanding this division is critical for the correct operation of conditional constructs like the if statement, the ternary operator, or the logical AND and OR operators. There is a strictly limited list of falsy values, which includes the boolean false, the number zero 0, an empty string, the special values null and undefined, and the numeric value NaN. Any other value existing in the language is automatically considered truthy and behaves like true in logical conditions.

Special attention should be paid to complex data types such as arrays and objects. Beginner developers often mistakenly assume that an empty array or an empty object should be equivalent to falsy, but in JavaScript, any arrays and objects, even completely empty ones, are truthy values. This means that the check if ([]) will always execute successfully, which often becomes a source of unexpected code behavior. To explicitly convert any value to a boolean type in code, developers use the Boolean(value) constructor or double negation, which allows precise control over application logic and avoids hidden errors when evaluating conditions.

Was this answer helpful?

More questions in this topic

Related questions from other topics