BugForge
All lessons
Node.js · 04/19 6 min

JavaScript gotchas

The language quirks that turn into one-line bugs.

[10, 9, 1].sort();            // [1, 10, 9]  (string order!) → use (a, b) => a - b
"5" + 1;                      // "51"        → Number(x) first
0.1 + 0.2 === 0.3;            // false       → compare with an epsilon, or use integer cents
typeof null;                  // "object"
new Date(2024, 1, 1);         // February: months are 0-based
parseInt("08");               // 8, but pass the radix: parseInt(x, 10)
[] == false;                  // true        → always use ===
Math.max();                   // -Infinity   (empty input)
arr.indexOf(x) > 0;           // misses index 0 → use !== -1 or includes()

Reference vs value

const a = [1, 2]; const b = a; b.push(3);  // a is [1, 2, 3] too
const copy = { ...obj };                    // shallow: nested objects are shared
const grid = Array(3).fill([]);             // ❌ three references to ONE array
const grid2 = Array.from({ length: 3 }, () => []); // ✅

this

Methods passed as callbacks lose this: setTimeout(obj.method, 0). Use an arrow or .bind(obj).

Closures in loops

for (var i…) shares one i across callbacks; let gives each iteration its own.

Practise it now
Next in Node.js
Modules: require, import and the cache