r/learnjavascript • u/Apart-Scientist-8590 • May 18 '26
Do people still use var in JavaScript?
I usually see let and const everywhere, and I understand why they are preferred because they are block-scoped and safer.
But I also heard an opinion that var can still be useful when declaring variables inside a function, because it makes it clear that the variable belongs to the whole function scope and may be used across different blocks inside that function.
For example, let feels more natural for variables inside blocks like if, try/catch, loops, etc., while var could theoretically show that the variable is intended to be available throughout the function. Does anyone actually think about var this way, or is var basically avoided completely in modern JavaScript?
View all comments
Show parent comment
6
u/theQuandary May 19 '26 edited May 19 '26
Let and Const are hoisting with extra steps (but nobody talks about it).
JS conceptually stores all function values in a closure object. When the function is about to be instantiated, that object must be created and must contain ALL the variables in the function's scope.
In the case of
var, all your variables except some function parameters and nested function declarations are set toundefinedin that closure object. When you access a variable, it's literally "get this and return its value".In the case of
let, your variable is instantiated to a pointer to an internal__really_undefinedvariable and conceptually must check every access. In reality, there are some special cases where you can prove the let doesn't need to be checked, but in those cases, the JIT turns let into var internally (the v8 team released an entire paper where they did in-depth optimization a couple years ago to lower the cost of let/const, but the final result was still something like 3-8% performance hit when you use them). EDIT: I'd add that pretty much the only time they can optimize is when the let/const are at the very top of the scope, but nobody has problems with understanding var at the top of the scope either.Branches and pointer indirection are the most costly things you can do in normal computing. Let/const require extra of both every time you use them.
constis slightly worse because it not only needs to check for use before define on every access, but aalso adds redefine checks too. Even worse,constis a const pointer rather than a const value which means its only truly constant if it is pointed at an immutable primitive. This is a bigger footgun than hoisting ever was (before I get the "but this is easy to teach" reply, I'd point out that hoisting is also easy to teach and has the side effect of helping new programmers understand how closures work and has to be taught anyway because all variables hoist).