## đ§ 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)