## 🧠 Introduction
JavaScript is one of the most powerful—and sometimes quirky—languages in modern development. Whether you're a beginner or a seasoned dev, these subtle behaviors can cause unexpected bugs.
Let’s dive into 7 common “gotchas” and how to handle them like a pro.
1️⃣ NaN
is Not Equal to Itself
console.log(NaN === NaN); // false
😲 Yes, NaN
is the only value in JavaScript that is not equal to itself.
✅ Use Number.isNaN(value)
instead:
Number.isNaN(NaN); // true
2️⃣ typeof null
is 'object'
console.log(typeof null); // 'object'
🧠 This is a long-standing bug in JavaScript and won’t be fixed due to backward compatibility.
✅ Always explicitly check for null
:
if (value === null) { // handle null }
3️⃣ [] + []
Returns an Empty String
console.log([] + []); // ''
Because arrays are coerced to strings, and []
becomes ''
, the result is an empty string. Wild, right?
4️⃣ [] == ![]
is true
console.log([] == ![]); // true
👉 Why? JavaScript performs weird coercions here. ![]
becomes false
, and [] == false
becomes true
due to type coercion.
✅ Use strict equality (===
) to avoid this.
5️⃣ Function Declarations Inside Blocks (❌ ES5 Pitfall)
if (true) { function sayHi() { console.log("hi"); } } sayHi(); // Throws in strict mode
✅ Avoid declaring functions inside blocks. Use function expressions instead:
if (true) { const sayHi = () => console.log("hi"); }
6️⃣ Implicit global
Variables
function foo() { bar = 5; // No 'let', 'const', or 'var' } foo(); console.log(bar); // 5 (attached to global object 😱)
✅ Always declare variables with let
, const
, or var
.
7️⃣ Objects as Keys Are Converted to Strings
const obj = {}; const key = {}; obj[key] = "value"; console.log(obj); // { "[object Object]": "value" }
✅ Use Map
when you want objects as keys:
const map = new Map(); map.set({}, "value");
✨ Final Thoughts
JavaScript is beautiful—but it has quirks. Understanding these helps you avoid subtle bugs and write cleaner, more predictable code.
💬 Found this helpful? Leave a comment or share your favorite JS gotcha!
Top comments (0)