Javascript hoisting

Does javascript hoist the var keyword to the top of the javascript file as it does with function declaration and not function expression?
and is that the main reason why let is preferred over var?

var declarations are hoisted to the beginning of their scope, be it a global or a declaration within a function. However, only the initialization is hoisted - the actual value assignment remains where it is.

This is (i think) because of the way javascript used to optimize. Your code in the browser is “just-in-time” compiled, so parsed and converted to machine code on the fly. Part of doing that is creating a “lookup table”, a space in memory where variable references will be stored. And var types are placed there during parsing (before the function actually runs), while let and const are placed there when the execution happens, on demand.

I think of it like reading a book series: know how some books include a cast of characters up front? They are vars, hoisted from where they appear in the book. You don’t get the character till you meet then in the process of reading, but their namespace has been set aside.

And function foo[...]{...} creates a var named foo for you, which is why it hoists.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.