Parts | Js The Weird
Welcome to the weird parts. Let’s start with the most infamous party trick.
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. js the weird parts
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. Welcome to the weird parts
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: It compares both value and type
You are not alone. JavaScript is the quirky, misunderstood genius of the programming world. It was built in 10 days, it drives the modern web, and it has a list of "features" that look more like 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.
