For a beginner in JavaScript, it's quite usual to come across the term "Hoisting in JavaScript", Before going into further details lets, have a look at an example. Below, a function is created and invoked:
function cowSays(sound){
console.log(sound);
}
cowSays('moo');
As one may expect, when the function "cowSays" is invoked by passing a string 'moo' as an argument, the function logs the passed string and the output in the case is 'moo'.
cowSays('moo');
// moo
But, what if we try to invoke the function before it is actually declared?
cowSays('moo');
function cowSays(sound){
console.log(sound);
}
Unexpectedly, the function gets called again and 'moo' is returned as the output to the console.
cowSays('moo');
// moo
This is what is known as hoisting in JavaScript.
So, what did we just see? Usually, people describe hoisting as declarations moving at top of the code. Although, it is something that appears to be happening. But technically, the code never moves anywhere. Such magic doesn't exist yet.
What actually happens is the declarations of the functions and variables are added to the memory at the time of compilation.
In the above given example, since the function declaration is added to the memory during the compile phase. In the example above, since the declaration of functions is added to the memory at the compile time, We were able to access them even before the place they were declared.
Now, Let's have a look at another example with a different variable:
Typically, one should declare then initialize the variable, and then should attempt to make use of it:
var a = 3;
console.log(a);
// 3
However, what will happend, if the variable is declared at the bottom of the code?
a = 3;
console.log(a);
var a;
// 3
The example above logs the output as '3'
But, How about the below example in which we declare and initialize the variable right at bottom of the code?
console.log(a);
var a = 3;
// undefined
This is where something unexpected happenes for the first time and we getthe output as 'undefined' instead of '3'.
The above case happens because 'Javascript hoists just the declarations and avoids the initializations'.
When a variable is intitalize and declare say, 'var a = 3', JavaScript hoists only the declaration part and thus 'a=3' is not hoisted and therefore not added to the memory.
If we declare and initialize a variable, say var a = 3;
, only the var a;
portion (the declaration) is going to be hoisted. The a = 3;
(the initialization) is not hoisted and therefore not added to memory.
As we know, when the variable is declared but not initialized, the variable is automatically initialized to 'undefined'. And, thus in the abpve example var a is set to 'undefined' and not '3'.
console.log(a);
var a = 3;
// undefined
In fact, the code is complied as:
var a;
console.log(a);
a = 3;
// undefined