Hoisting in Javascript
Ever wondered how the undefined gets set to a variable when declared but not initialised or a function that gets executed even before its declaration?
Yes, I was one of them who used to think how a variable that was never initialised has a value called undefined in it when I first started with Javascript.
Variable hoisting
Let's look at a very simple example code below
this outputs undefined to the console, as per MDN, undefined is a primitive value automatically assigned to variables that have just been declared.
The process of assigning the primitive undefined values to declared variables is called hoisting in Javascript.
Let’s look at when exactly hoisting happens when a javascript code gets executed.
Before I talk about this, I need to touch a concept called execution context in Javascript. Execution context is an abstract concept of an environment where the Javascript code is evaluated and executed in two different stages
- creation phase
- execution phase (I won’t be talking about execution phase in this post)
Creation phase is where the variable and function declarations are put into memory, but stay exactly where you have written them in your code. In the creation phase, all variables that are declared but not initialised with a value will be assigned undefined
by javascript engine.
That is how we see undefined value for variables that are not initialised but used in your code.
As a good practice, avoid initialising variables with undefined in your code.
Function hoisting
Functions also get allocated in memory during creation phase, which will allow us to use a function before it is declared in the code.
For example:
Let's look at above code example, I called the function in my code first, even before the function is written, the code still works. This is because of execution context in JavaScript.
One thing to keep in mind about hoisting is, only declarations get hoisted in JavaScript, not the initialisations.
I hope this post helps to understand and clear confusion about variable and function hoisting in JS.
Top comments (0)