Hoisting in a nutshell
We will cover the question what is hosting and how does it work in today´s in a nutshell beginners lesson.
Table of Contents
The Hoisting
Lets have a look at the following code:
1 | var myVariable = 'My variable gets alerted!'; |
Try it in your favorite browser. Open the developer tool and paste both lines of code and confirm. (Important to know is that if you want to write multiple line commands you can use Shit-Enter
to get into a new line.) What happens? Easy, in your console it outputs the value of myVariable
, because the variable gets defined before its used.
Other nice online tools to test this, if you dont want to use the browser, is repl.it or JS Bin.
Now, lets switch both lines and call console.log
right before we declare and assign myVariable
.
1 | console.log( myVariable ); |
It gets undefined, but there is still some hoisting going on. There is hoisting, but my variable is undefined, how?
Variable declaration vs definition
We have to define two things to understand:
1 | var myVariable; //declaration of myVariable |
In your eyes this looks like one statement, but the engine of JavaScript treats it as two, namely the declaration var myVariable
and the assignment myVariable = 'xyz'
. The declaration gets hoisted, but the assignment is still in place, thats why the variable is undefined
.
Function hoisting
The same principle applies to functions:
1 | function myFunction() {...} // a function declaration (gets hoisted completely) |
That means the whole function body gets moved to the top and allows to call a function before it gets declared:
1 | hoistIt(); //output: This function declaration gets hoisted. |
Take home message
- Declarations, variables and functions, are always hoisted to the top (of the scope) before execution
- Definitions (variable) and expressions (function) stay in place
Best practice
for writing code therefore is:
Manually declare variables at the beginning of the current scope (like e.g. functions), and declare functions before calling them, it resembles the default behavior of the JavaScript engine.
1 | function manual( argument ) { |