On JavaScript's Weirdness

https://news.ycombinator.com/rss Hits: 6
Summary

“JavaScript sucks because '0' == 0!” - literally everyone ever Sure, that part of JavaScript sucks, but every JS setup these days contains a linter that yells at you for code like that. Instead, I want to talk about some of the weirder quirks of JavaScript — those that are much more insidious than that — the kind of stuff you wouldn't find on r/ProgrammerHumor or a JS tutorial. All of them can occur in any JavaScript/ECMAScript environment (so browser, Node.js, etc.), with or without use strict enabled. (If you're working on legacy projects without strict mode, you should run. And if you don't know where to: Stack Auth is hiring.) #1. eval is worse than you think How silly it would be to think that these two are the same: function a(s) { eval("console.log(s)"); } a("hello"); // prints "hello" function b(s) { const evalButRenamed = eval; evalButRenamed("console.log(s)"); } b("hello"); // Uncaught ReferenceError: s is not defined The difference is that the former has access to variables in the current scope, whereas the renamed version can only access the global scope. Why? Turns out that ECMAScript's definition for function calls has a hardcoded special case, which runs a slightly different algorithm when the function invoked is called eval: I can't stress enough how insane it is to have this hack in the specification for every single function call! Although it goes without saying that any half-decent JS engine will optimize it, so while there is no direct performance penalty, it certainly makes build tools & engines more complicated. (As an example, this means that (0, eval)(...) differs from eval(...), so minifiers must consider this when removing seemingly dead code. Scary!) #2. JS loops pretend their variables are captured by value Yes, the title makes no sense, but you'll see what I mean in just a second. Let's start with an example: for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i)); } // prints "0 1 2" — as expected let i = 0; for (i = 0; i < 3; i+...

First seen: 2025-04-04 12:00

Last seen: 2025-04-04 17:02