Truthy, Falsy, and Type Coercion in JavaScript: Avoid Bugs with Clear Logical Evaluations

Truthy, Falsy, and Type Coercion in JavaScript: Avoid Bugs with Clear Logical Evaluations




1️⃣ What Are Truthy and Falsy Values?

In JavaScript, every value is either truthy or falsy when evaluated in a boolean context (like if, while, &&, ||, !).

🔸 Falsy Values (Only 7):

false 0 -0 0n // BigInt zero "" // empty string null undefined NaN

Everything else is truthy — including empty arrays [], empty objects {}, and even "0".


if ("0") console.log("Truthy"); // if ([]) console.log("Truthy"); //


2️⃣ Type Coercion in JavaScript: Implicit and Explicit

Type coercion is the automatic (or implicit) conversion of values from one data type to another.

🔹 Implicit Coercion

"5" + 1 // "51" → string "5" - 1 // 4 → number true + 1 // 2 false == 0 // true (⚠️)

🔹 Explicit Coercion

Number("5") // 5 String(100) // "100" Boolean("") // false

✅ Use explicit coercion for clarity and safety.


3️⃣ Equality: == vs ===

  • == → Loose equality (with coercion)

  • === → Strict equality (no coercion)

0 == false // true (⚠️) 0 === false // false "" == false // true (⚠️) "" === false // false

✅ Always use === unless you have a strong reason not to.


4️⃣ Logical Operators and Double Negation

Logical operators convert values to boolean when necessary.

🔹 OR (||)

Returns the first truthy value

const name = user.name || "Guest";

🔹 AND (&&)

Returns the first falsy value


const isLoggedIn = user && user.isActive;

🔹 Double NOT (!!)

Converts any value to a strict boolean:


!!"hello" // true !!0 // false !![] // true


5️⃣ Real-World Use Cases and Pitfalls

Default values with OR:

function greet(name) { const userName = name || "Guest"; console.log("Hello, " + userName); }

Optional chaining + AND:

const email = user && user.contact && user.contact.email;

Common Pitfall:

false || "value" // returns "value", but what if false is valid?

✅ Prefer nullish coalescing (??) for better safety:

false ?? "default" // false ✅ null ?? "default" // "default"



This Content Sponsored by Buymote Shopping app

BuyMote E-Shopping Application is One of the Online Shopping App

Now Available on Play Store & App Store (Buymote E-Shopping)

Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8

Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication

Previous Post Next Post