Does automatically hoisting slow down the performance of JavaScript?

Viewed 494

Lately, I was studying Scope in Javascript. I want to know whether automatically hoisting is done at compile time or at the time of executing the code(run time). If it does at run time then I have another question does auto-hoisting will slow down the performance of the Javascript program.

something = a(); 
function a(){
 console.log("hoisting");
 return 10;
}
var something; 

Should we use manual hoisting or it would be better to use automatically hoisting?

3 Answers

As I know, There are no performance issues. The initializations are getting done in compile time. So doesn't matter you initialize on top or bottom, The JS engine will create the references in compile time.

BUT

If you forgot to initialize at the bottom, It will be initialized as undefined by default. Because of hoisting it’s considered a practice to declare functions or variables at the top of their respective scopes.

JavaScript: What is Hoisting? (Recommended)

To put my comments as an answer:

People have a different understanding of what hoisting supposed to mean. Fact is that, according to the spec, every time a function is called a new execution context is created, which holds a new environment. Then the function body is processed to find all variable declarations (var, let, const (and function declarations)) and bindings for those names are created in the new environment. var declarations are initialized with undefined. Then the body is actually evaluated.

Considering this, from the perspective of the engine it doesn't really matter where you place the var declaration, the whole body has to be processed anyway.

Having said that, I would be surprised if actual implementations didn't cache that information. After all, the variable declarations in a function don't change between function calls.

It is not done at run time. It's in the compile process. So it doesn't slow down the performance. Just before the code is executed the compiler scans for all variable and function declarations and allocates them in the memory.

Related