Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does automatically hoisting slow down the performance of JavaScript?

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?

like image 477
Subrato Pattanaik Avatar asked Dec 14 '22 07:12

Subrato Pattanaik


2 Answers

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.

like image 93
Felix Kling Avatar answered May 16 '23 07:05

Felix Kling


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)

like image 40
BadPiggie Avatar answered May 16 '23 09:05

BadPiggie