function showThis() { console.log(this); } showThis(); // window (or undefined in strict mode)
If you’ve spent more than five minutes writing JavaScript, you’ve probably had a moment where you stared at your screen and whispered, “...why?”
console.log([] + []); // "" (empty string) console.log([] + {}); // "[object Object]" console.log({} + []); // 0 (wait, WHAT?) The last one is a parsing quirk. In some engines, {} at the start of a line is treated as an empty block, not an object. So {} + [] becomes + [] which coerces to 0. Never, ever trust == . It’s like asking a toddler if two things are the same. js the weird parts
function oops() { accidentalGlobal = "I'm everywhere now"; } oops(); console.log(window.accidentalGlobal); // "I'm everywhere now" You didn't use var , let , or const ? Congratulations, you just polluted the global object. This is why we have linters and "use strict" . The this keyword is like a chameleon on caffeine. Its value depends entirely on how a function is called.
console.log(isNaN(NaN)); // true // But wait... console.log(isNaN("hello")); // true (because "hello" can't be a number) That’s why ES6 gave us Number.isNaN() which actually behaves. In many languages, if you forget to declare a variable, you get an error. In JavaScript (non-strict mode), you get a present : function showThis() { console
It gets weirder:
const bound = showThis.bind("hello"); bound(); // String {"hello"} Never, ever trust ==
So next time you see [] + [] returning "" , don’t cry. Laugh. Then fix it. And remember: you’re not alone. What’s the weirdest JavaScript bug you’ve ever encountered? Hit reply or drop a comment—I’d love to compare war stories.