DEV Community

Shahzaib ur Rehman
Shahzaib ur Rehman

Posted on

7 Subtle JavaScript Behaviors That Can Trip You Up (And How to Avoid Them

## 🧠 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 
Enter fullscreen mode Exit fullscreen mode

😲 Yes, NaN is the only value in JavaScript that is not equal to itself.

✅ Use Number.isNaN(value) instead:

Number.isNaN(NaN); // true 
Enter fullscreen mode Exit fullscreen mode

2️⃣ typeof null is 'object'

console.log(typeof null); // 'object' 
Enter fullscreen mode Exit fullscreen mode

🧠 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 } 
Enter fullscreen mode Exit fullscreen mode

3️⃣ [] + [] Returns an Empty String

console.log([] + []); // '' 
Enter fullscreen mode Exit fullscreen mode

Because arrays are coerced to strings, and [] becomes '', the result is an empty string. Wild, right?


4️⃣ [] == ![] is true

console.log([] == ![]); // true 
Enter fullscreen mode Exit fullscreen mode

👉 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 
Enter fullscreen mode Exit fullscreen mode

✅ Avoid declaring functions inside blocks. Use function expressions instead:

if (true) { const sayHi = () => console.log("hi"); } 
Enter fullscreen mode Exit fullscreen mode

6️⃣ Implicit global Variables

function foo() { bar = 5; // No 'let', 'const', or 'var' } foo(); console.log(bar); // 5 (attached to global object 😱) 
Enter fullscreen mode Exit fullscreen mode

✅ 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" } 
Enter fullscreen mode Exit fullscreen mode

✅ Use Map when you want objects as keys:

const map = new Map(); map.set({}, "value"); 
Enter fullscreen mode Exit fullscreen mode

✨ 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)