mystery javascript

here's a puzzle. find a value for x which makes the below function return true.

x => x == !x

there are probably a lot of solutions to the problem because javascript, but the answer i had in mind is []. the reason for this relies on two javascript features, truthiness and lenient equality.

truthiness is a feature of javascript for writing concise code. many other languages incorporate it because it's pretty nice. a few values are interpreted as "falsy", meaning they are interpreted as false when treated as a boolean. all other values are treated as "truthy". this is mostly used for conditional code where you don't want to write x != 0 or x != '' or whatever.

the specific set of values which are falsy are the two null values null and undefined (makes sense), the numbers 0, NaN and 0n (the bigint version; people should use bigints more), the empty string '', and possibly some other things. the empty array and the empty object are not treated as falsy, which makes sense because they're reference types. since [] is truthy, ![] is false.

thus [] == ![] is equivalent to [] == false, which happens to be true because == works in mysterious ways. one might expect it to return false for all truthy values but i guess the people designing the specs decided it might be useful to treat an empty array as false in this scenario. (this doesn't apply to {}, though. i have absolutely no clue why. maybe they just thought that wouldn't be very useful? i don't know. javascript doesn't make that much sense.)

cc0 everything on this site is freely available under CC0 1.0 Universal.

home blog