They cite a surprising 8% performance boost in some cases by using var.
They did a great job of explaining javascript variable hoisting, but that's all that they have explained.
Isn't that part still the crux of the article as it contains the answer to the title?
They are only talking about one javascript engine (node). They didn't test any other engine or go into the implementation in node. For all we know, this might just be a poorly optimized code path in node that needs a little love, but the author didn't bother doing any investigation.
Looking at the linked github issue, jsc doesn't have the performance penalty. It would have been interesting if the author had investigated why and shared that with us.
If this article is about hoisting then this is a well-made high-effort high-value article. If this article is about performance then this is a low-effort low-value summary of a github issue they read.
Also node used the v8, the same engine as chromium. So this doesn't just affect node, it also affects the majority of the browser share market. oh, and deno uses v8 too.
? There is no mention of hoisting in the article, not the name or the concept. I am not even sure the author knows the concept of hoisting and that 'let' and 'var' behave differently. All the examples are suspiciously missing the key differences, and all the surrounding text is about the scope of the if construct.
> As of TypeScript 5.0, the project's output target was switched from es5 to es2018 as part of a transition to ECMAScript modules. This meant that TypeScript could rely on the emit for native (and often more-succinct) syntax supported between ES2015 and ES2018. One might expect that this would unconditionally make things faster, but surprise we encountered was a slowdown from using let and const natively!
So they don't transpile to ES5, and that is the issue.
I can always rely on FAANGs to make things unnecessarily confusing and ugly.
The good news is that we can still write our Scala `val`s and `var`s (`const` and `let`) in the source code, enjoying good scoping and good performance.
Usage of Scala itself is less shiny if you look at market share. But I believe it's still growing in absolute numbers, only quite slowly.
Wow! 4 out of 20 total ain't bad!
Jocking aside the starting set (Scala developers) is already small, so it's not like either it or even less Scala.js is going to be a major player anytime soon.
Is that still true? Early versions of V8 would do scope checks for things that weren't declared with var but it doesn't do that any more. I think const and let are lowered to var representation at compile time now anyway, so when the code is running they're the same thing.
In
function example(measurement) {
console.log(calculation); // undefined - accessible! calculation leaked out
console.log(i); // undefined - accessible! i leaked out
<snip>
Why does the author say `calculation` and `i` are leaking? They’re not even defined at that point (they come later in the code), and we’re seeing “undefined” which, correct me if I’m wrong, is the JS way of saying “I have no idea what this thing is”. So where’s the leakage? function example(measurement) {
console.log(calculation); // undefined - accessible! calculation leaked out
console.log(i); // undefined - accessible! i leaked out <snip>
It's "leaking" because the variable is in scope, it's associated value is "undefined". This is different than with let/const where the variable would not be in scope at that point in the function. An undefined value bound to a variable is not the same as "I have no idea what this thing is". That would be the reference errors seen with let/const.There are some relatively simple heuristics where you can tell without escape analysis that a variable will not be referenced before initialization.
The obviously bad constructions are references in the same scope that happen before the declaration. It'd be nice if these were an early errors, but alas, so keep the TDZ check. The next is any closed over reference that happens before the initializer. These may run before the initializer, so keep the TDZ check. Then you have hoisted closures even if they're after the initializer (eg, var and function keyword declarations). These might run before the initializer too.
But everything else that comes after the initializer: access in the same or nested scope and access in closures in non-hoisted declarations, can't possibly run before the initializer and doesn't need the TDZ check.
I believe this check is cheap enough to run during parsing. The reason for not pursuing it was that there wasn't a benchmark that showed TDZ checks were a problem. But TypeScript showed they were!
I laud the recent efforts to remove the JS from JS tools (Go in TS compiler, esbuild, etc), as you don't need 100% of your lang utils written in the same interpreted lang, especially slow/expensive tasks like compilation.
Consider
console.log(foo)
let foo
vs console.log(foo)
var foo
I think the article confuses "in scope" with "declared", and "declared and initialised" with "initialised". local x = 42
do
print(x) -- 42
local x = x * 2
print(x) -- 84
end
print(x) -- 42
Look, ma! No dead zones!
taejavu•4mo ago
throw-the-towel•4mo ago
samus•4mo ago
Aurornis•4mo ago
It’s much easier to reason about when your variables aren’t going to escape past the end of the block.
In non-GC languages going out of scope can also be a trigger to free the contents of the variable. This is useful for situations like locking where you can put the minimal span of code that requires the lock into a scope and take a lock which automatically unlocks at the end of the scope, for example.
JavaScript’s hoisting and scoping feel natural to people who started in JS, but most people who came from other languages find it surprising.
mjmas•4mo ago
thaumasiotes•4mo ago
What would be the advantage over the system used everywhere else?
happytoexplain•4mo ago
To avoid having to memorize yet one more thing that doesn't have an obvious benefit.
>An explicit construct for scoping would have been so much clearer to me
Having an additional construct for scoping is clearer than having every set of already-existing curly braces be a new scope? That seems backwards.
1718627440•4mo ago
Yes, maybe we could use something similar to parenthesis. Maybe they can look curly. /s
sfink•4mo ago
TDZ is also terrible because the engines have to look up at runtime whether a lexical variable's binding has been initialized yet. This is one reason (perhaps the main reason?) why they're slower. You can't constant fold even a `const`, because `const v = 7` means at runtime "either 7 or nothing at all, not even null or undefined".
In my opinion, TDZ was a mistake. (Not one I could have predicted at the time, so no shade to the designers.) The right thing to do when introducing let/const would have been to make any capture of a lexical variable disable hoisting of the containing function. So the example from the article (trimmed down a little)
would raise a ReferenceError for `useX`, because it has not yet been declared at that point in the syntactic scope. Same with the similar which in current JavaScript also either returns 1 or throws a ReferenceError. I'm not against hoisting functions, and removing function hoisting would have not been possible anyway. The thing is, that's not "just a function", that's a closure that is capturing something that doesn't exist yet. It's binding to something not in its lexical scope, an uninitialized slot in its static environment. That's a weird special case that has to be handled in the engine and considered in user code. It would be better to just disallow it. (And no, I don't think it would be a big deal for engines to detect that case. They already have to compute captures and bindings.)Sadly, it's too late now.
taejavu•4mo ago
Jtsummers•4mo ago
There are several examples in the blog, and only one is the first. It does not include the "terrible" descriptor after it. So your comment is kind of odd because it doesn't connect to the article at all.
If you mean the first example that's described as "terrible", that's the second example and it's the one with the leaking loop variable. It kind of is terrible, Python has the same problem (and many others, Python scoping rules are not good). C used to have that problem but they at least had the good sense to fix it.
taejavu•4mo ago
thayne•4mo ago
There isn't a difference between lexical scope and "block" scope. What I think you are referring to as "block" scope, is a subset of lexical scope. The difference between var and let/const is where the boundaries of the lexical scope is.
sfink•4mo ago
I was really using your comment as a jumping off point for my rant.
I wouldn't describe `var` declarations as lexical, though. Sure, they have a lexical scope that they get hoisted up to cover, but hoisting is not "just lexical scope". It's unusual.
chatmasta•4mo ago
It basically means you can always override anything, which allows for monkey patching and proxying and adapter patterns and circular imports… These are all nasty things to accidentally encounter, but they can also be powerful tools when used deliberately.
These hoisting tricks all play an important role in ensuring backwards compatibility. And they’re the reason why JavaScript can have multiple versions of the same package while Python cannot.
sfink•4mo ago
You can't monkey patch lexicals, that is much of their point. Any reference to a lexical variable is a fixed binding.
In practice, this comes up most often for me when I have a script that I want to reload: if there are any toplevel `let/const`, you can't do it. Even worse, `class C { ... }` is also a lexical binding that cannot be replaced or overridden. Personally, I normally use `var` exclusively at the toplevel, and `let/const` exclusively in any other scope. But `class` is painful -- for scripts that I really want to be able to reload, I use `var C = class { ... };` which is fugly but mostly works. And yet, I like lexical scoping anyway, and think it's worth the price. The price didn't have to be quite so high, is all. I would happily take the benefit of avoiding TDZ for the price of disabling hoisting in the specific situations where it no longer makes sense.
I agree that hoisting is a backwards compatibility thing. I just think that the minute optional lexical scoping entered the picture, hoisting no longer made sense. Either one is great, the combination is awful, but it's possible for them to coexist peacefully in a language if you forbid the problematic intersection. TDZ is a hack, a workaround, not peaceful coexistence. (TDZ is basically the same fix as I'm proposing, just done dynamically instead of statically. Which means that JS's static semantics depend on dynamic behavior, when the whole point of lexical scoping is that it's lexical.)
chatmasta•4mo ago
True, but you can at least wrap the entire scope and hack around it. It's not gonna be pretty or maintainable but you can avoid/override the code path that defines the let.
Anecdotally... I've monkeypatched a lot of JavaScript code and I've never been stopped from what I wanted to do, whereas with Python I've hit a dead-end in similar situations. Maybe there's some corner case that's unpatchable but I really think there is always a workaround by the ability to wrap the scope in a closure. Worst case you re-implement the entire logic and change the bit you care about.
minitech•4mo ago
The premise of “a language like Python that works as you describe” is wrong too, since Python doesn’t work like that (it has the same hoisting and TDZ concepts as JavaScript):
ngruhn•4mo ago
mjmas•4mo ago
sfink•4mo ago
My solution would only stop hoisting closures that capture lexicals, with the idea that capturing a lexical means that the closure's identity is now tied to that lexical environment anyway so it's kind of bizarre to hoist it out to where part of its identity is missing.
But you were giving a simplified example, so I want to be sure I'm not dismissing your concern unfairly. This would not work:
Hm... you raise a good point, though. Should this work?: perhaps the proposal needs to be modified: instead of not hoisting lexical closures (functions that close over lexicals) at all, hoist them to the nearest lexical scope containing everything they close over. So the above would work, but this would still be an error: Not that I'm proposing anything at all, this is all wishful thinking. Though I've wondered if there could be a way to opt-in to this somehow, something like: (or `const function`, I suppose, but I don't know if there's a useful distinction.) Then these lexical functions would never need to consider the case where they capture uninitialized bindings. But that's kind of weird, in that `let f = () => { ... };` looks similar to `let function f() { ... }` but the former would still have to hoist. Bleagh. Oh well.prmph•4mo ago
I wish there was explicit support for this though, maybe with a construct like <exression> where <antecedent>, etc, like what Haskell has, instead of having to hack it using functions and var
happytoexplain•4mo ago
jvanderbot•4mo ago
bigstrat2003•4mo ago