JavaScript Truthy Arrays in If Statements Explained

🌙 Evening Post — Why This if Block Always Runs This morning’s code was: let a = []; if (a) { console.log("Yes"); } else { console.log("No"); } 💡 Correct Output Yes This surprises many people 😄 Let’s understand why step by step. 🧠 Simple Explanation : 🔹 Key Rule in JavaScript 👉 In JavaScript, all objects are truthy. And: [] // is an object Even though the array is empty, it still exists in memory. So JavaScript treats it as: true 🔹 What happens in the if condition? if (a) Here: a is [] [] is truthy So the if block runs 👇 console.log("Yes"); That’s why the output is: Yes ❗ Common Mistake Beginners Make Many people think: Empty array [] → falsy ❌ Empty object {} → falsy ❌ But actually: [] → truthy ✅ {} → truthy ✅ Only these are falsy in JS: false 0 "" (empty string) null undefined NaN 🎯 Key Takeaways : Empty arrays are truthy Empty objects are truthy Truthy/falsy is about type, not size This question appears often in interviews 📌 If you want to check if an array is empty, do this instead: a.length === 0 💬 Your Turn Did you expect "Yes" or "No"? 😄 Comment “Got confused 😅” or “Clear now ✅” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #Basics #TechWithVeera #WebDevelopment

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories