DEV Community

Cover image for UNDERSTANDING THE HOISTING CONCEPT IN JAVASCRIPT
Hakeem Abdul
Hakeem Abdul

Posted on • Updated on

UNDERSTANDING THE HOISTING CONCEPT IN JAVASCRIPT

HOISTING IN JAVASCRIPT

Before i go in to explaining what hoisting is and how it works on a javascript engine, i would like to give a definition of an important term in javscript called the execution context.The execution context is somewhat like a global wrapper that contains and handles the multiple codes that runs on our javascript engine. The execution context controls the order and the path through which codes are processed in the 'Behind-the-scenes part of the engine'. Whenever code is run in javascript, it is run inside the execution context.

Note that the execution context is an abstract concept that illustrates an enviroment where the codes you write runs and gets executed in your javascript engine.

This execution context works in two phases basically in the javascript engine 
Enter fullscreen mode Exit fullscreen mode
  1. Firstly, when the code is run, the execution context is created, then the javascript engine organizes and stores the variables and functions in a memory space .
  2. Secondly, it processes your code line after lines, reading and parsing the data on the line.

NOTE:

-The first step describes the term "hoisting", but i would still like to explain further on this term, so i wouldnt stop reading just yet . There is more i would like you to get, to ensure you solidify your understanding of what "hoisting" means.
-The variables and functions are initially sitting in memory(existing) until they are being called into use, then the javascript engine retrieves them.
-Your code is not what is really given to the computer directly rather, it is translated and converted by the compiler to data that the computer system can understand and execute.

WHAT SEEMS LIKE BUT ISNT HOISTING

Contrary to how it may seem, hoisting isnt a default response of javascript that physically moves the declarations of variables and functions to the top stack of your code to run.

EXAMPLE 1
Alt Text

From this example, it can be seen that in the code, the function has been called from the top and the variable outputed from the top using the console.log.

Alt Text

Looking at the result in the console of the browser, the function has been called but the variable is 'undefined'. Why did only the function work?, does hoisting only work for functions?, you might ask. But the fact is that hoisting actually works for both of them and it did work! but it just didnt give what you'd expect. The reason for this is that

When your code was run, the execution context was created(that abstract enviroment where codes are managed and compiled) in two phases; storing the functions and variables, and then processing the code.

The function was stored in 'whole', meaning that the function itself(myFunction) and the string data it held("function has been called") were all stored in memory for use.

And so it didnt matter that it was called some lines before actually getting to the function itself because during the first phase of the execution context, it was already existing in memory.

But in the case of a variable, it is not the same story. This is because only the declaration of the variable(var x) was setup and stored in memory, the initialization(var x ="Variable has been called") wasnt stored. This is because by default, javascript doesnt know finally what your variable might be set to and doesnt want to make that desicion for you while storing, therefore it initially set the data of the variable to undefined in memory. So when the execution context was created in the first phase, it set up a memory space for the variable x and set the value to the special keyword 'undefined' and when executing in the second phase by processing the code from the top line by line, it sees that the variable x is being outputed(printed out) before assigned to any data and therefore retrieves the default data of 'undefined' and set the variable to it.

NOTE:

All variables in javascript are initially set to undefined and will get outputed as so except the data of the variable has been set before 'console.logging' it on your browser.

Another thing to understand is that there is a difference in results between declaring a variable without assigning anything to it and not declaring a variable at all when trying to output it on the console of your browser.

EXAMPLE 2

CASE 1: DECLARING A VARIABLE WITHOUT ASSIGNING

Alt Text

In this case, it can be seen in the code that the variable has been declared but without any value assigned to it.

Alt Text

And as you would deduce from the previous explanation, the results in the console of the browser was outputed as undefined because it doesnt matter when the code is executed from top to bottom if there is a value assigned or not as the initial value will be set to undefined except the initialization was set before outputing it('console.logging').

CASE 2 : NOT DECLARING AT ALL

Alt Text

In this case, the variable hasnt been declared but is being outputed from the code. The results in the browser is as thus,

Alt Text

Now, from the console of the browser, we are getting an 'Uncaught ReferenceError' message saying x hasnt been defined(declared or initialized).

Ok but hol up now, what is the difference between the word 'Undefined' in the first case and this second case where there is an error showing that the variable x has not been defined. Now, there is something you need to understand about this two results.

Undefined is a javascript data type, it is a special key word that means that a variable has not been set to a value(has not been defined to mean or represent anything yet), but on the other hand , the result in case 2 is an error message that alerts you that the variable you are trying to output doesnt exists in the first place and so isnt defined to mean anything in your code.

CONCLUSION:

Hoisting is a default response in javascript where your functions(including its data) and variables(excluding its data) are stored and used up they are being called irrespective of the fact that they are below the code you use to call them up.

This is my personal definition of it anyways and the way i understand it to be and hope you understand it the same way.

Although, hoisting is javascript slick way of helping you run your code regardless of what order you write,it is best you dont rely on it or use it on your code. Rather, the better and safe way of writing code in your functions and variables is declaring and initializing them before outputing it line by line . This will help you avoid bugs and errors in your code.

Alt Text

Alt Text

I hope this entry on what hoisting is has been helpful and efficient to your understanding. Thank you for reading and keep improving!!!

Follow me @ Twitter

Top comments (0)