Js The Weird Parts Fixed Here

console.log(0 == false); // true console.log("" == false); // true console.log(null == undefined); // true console.log(NaN == NaN); // false (yes, NaN is not equal to itself) The rule is simple: . It compares both value and type. The == operator tries to be "helpful" by converting types behind your back. That "help" is the source of countless bugs. NaN : The Loneliest Number Speaking of NaN (Not a Number), it has a personality disorder.

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?”

const arr = [1, 2, 3]; arr["foo"] = "bar"; console.log(arr); // [1, 2, 3, foo: "bar"] console.log(arr.length); // 3 (still!) The length property only counts numeric indices. The string key "foo" is there, but the array pretends it isn’t. JavaScript tries to be "helpful" with Automatic Semicolon Insertion (ASI). But sometimes, it helps too much. js the weird parts

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.log(this); } showThis(); // window (or undefined in strict mode) console

And arrow functions? They don’t have their own this at all—they inherit from the surrounding scope. Arrays in JS are just objects with numeric keys and a special length property. That means you can do... questionable things.

console.log(typeof NaN); // "number" Yes. The representation of "Not a Number" is technically a number. And as we saw, it refuses to be friends with anyone, including itself. The only reliable way to check for NaN is: That "help" is the source of countless bugs

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.