🔥 JavaScript Quirks That’ll Melt Your Brain

🔥 JavaScript Quirks That’ll Melt Your Brain

Ever seen '2' - 2 === 0 and '2' + 2 === '22' in the same language? Yep — that’s JavaScript.

Let’s break down the madness into patterns and principles, so the next time JS throws curveballs, you’re ready like a pro. ⚔️


📌 Pattern 1: String vs Number (Type Coercion)

JavaScript is dynamically typed and loves converting types behind the scenes.

console.log('2' - 2); // 0 (string converted to number) 

console.log('2' + 2); // '22' (number converted to string, then 

concatenated) console.log(2 + '2'); // '22' (same as above) 

console.log('2' * 2); // 4 (string becomes number) console.log('2' / 2); // 1 (same)        

🔍 Rule: + operator → string concatenation if one operand is a string -, *, / → force numeric conversion


📌 Pattern 2: Weird Math


console.log('10' - - '5'); // 15 // '10' - -'5' => 10 - (-5) => 15        

📌 Pattern 3: Falsy, Truthy & Unary Ops

console.log(+[]); 

// 0 ([] coerces to '' → number → 0) console.log(null + 1); // 1 (null //becomes 0) 


console.log(undefined + 1); 


// NaN (undefined becomes NaN)        

📌 Pattern 4: String Coercion with Arrays & Objects

console.log([] + 1); 


// '1' ([] → '' + 1 → '1') console.log([] + []); // '' (both empty arrays → '') console.log([] + {}); // '[object Object]' ('' + object → string) 



console.log({} + []);
 // 0 → interpreted as empty block + [] console.log(({}) + []); // '[object Object]' (object wrapped in parentheses)

        


👀 The + operator always tries to stringify objects if one side is non-numeric.


📌 Pattern 5: NaN & Type Oddities

console.log(NaN == NaN); // false (NaN is never equal to anything, even itself) console.log(typeof NaN); // 'number' (yup, it’s weird)        

📌 Pattern 6: Surprising Results

 console.log('b' + 'a' + + 'a' + 'a'); 

// 'banana' 




// 'b' + 'a' → 'ba' // + 'a' → NaN // 'ba' + NaN → 'baNaN' + 'a' → 'baNaNa'        
console.log(!![] + !![]); 

// 2 // !![] is true → true + true → 1 + 1        

✨ Bonus Pattern: Arrays Become Strings


console.log([1,2] + [3,4]); 
// '1,23,4' // Arrays → strings: '1,2' + '3,4' = '1,23,4'        

💬Conclusion

JavaScript is a magician — it converts types silently, treats objects and arrays as strings, and makes math with undefined things weirdly legal.

👉 Mastering these quirks is a rite of passage. If this post helped you see the light, give it a 🔁 repost or ❤️ like — and tag a JS buddy to blow their mind!


Want a poster version of this for your wall or a dev gift? Could you just DM me? 💻

#JavaScript #TypeCoercion #FunWithJS #WebDev #MindBlownJS #CodeSmart

To view or add a comment, sign in

Others also viewed

Explore topics