JavaScript traps · JavaScript
JavaScript: "5" + 3 = 53?!PRO
+ joins text, - only does maths. Plus [] + [] and [] + {}.
// "5" + 3 = 53 … but "5" - 3 = 2 ?!
// + joins text when either side is a string; - only does maths.
console.log("5" + 3); // "53" ?!
console.log("5" - 3); // 2
console.log(Number("5") + 3); // 8 ✓
console.log(+"5" + 3); // 8 ✓ (unary + converts)
// Bonus traps
console.log("5" * "2"); // 10
console.log([] + []); // "" (empty string)
console.log([] + {}); // "[object Object]"
Open code JS1 in Pocket Compiler
Download the Pocket Compiler app — free
No app yet? Install it, then open the app and type the code JS1 in Code Library.