Hello everyone!
Today we are going to see about the topic of truthy and falsy
Introduction: Everyday Logic in Code
- Start with a relatable hook (example: "Have you ever seen JavaScript behave strangely in an
if
condition?") - Introduce the idea that JavaScript doesn’t just use
true
andfalse
—it interprets many values in a boolean way. - Set the tone that this blog will uncover this “hidden logic”.
What Does ‘Truthy’ and ‘Falsy’ Mean?
- Define “truthy” = values that behave like
true
- Define “falsy” = values that behave like
false
- Mention it’s part of type coercion in JavaScript
The 7 Falsy Values in JavaScript
List and explain briefly:
false
0
-
""
(empty string) null
undefined
NaN
-
document.all
(rare case)
Example:
js
if (0) {
console.log("This won't run, because 0 is falsy");
}
Examples of Truthy Values
- Almost everything else is truthy: non-empty strings, arrays, objects, numbers other than 0
- Show some examples:
js
if ("hello") console.log("Truthy string");
if ([]) console.log("Truthy empty array");
Why This Matters in Real Projects
-
Show where truthy/falsy values sneak in:
- Conditionals
- Logical operators
||
,&&
- Ternary operators
- Default value fallbacks
Example:
js
let username = userInput || "Guest";
Common Mistakes Developers Make
- Using
==
instead of===
- Assuming empty arrays or objects are falsy (they’re truthy!)
- Forgetting
NaN
is falsy
How to Check If a Value is Truthy or Falsy
- Use
Boolean()
or double!!
: js console.log(Boolean("hello")); // true console.log(Boolean("")); // false
Conclusion: Logic You Now Understand
- Wrap up with how knowing truthy/falsy can help avoid bugs
- Encourage testing values and using strict equality when needed