What is JavaScript hoisting?
JavaScript hoisting
In JavaScript the variable and function declarations are put into memory during the compile phase. So, it can be accessed or used before we declare them in our the code.
Example of JavaScript variable hoisting
Lets consider following example:
console.log(firstname); var firstname; firstname = 'Joe'; // Output undefined
Explanation:
JavaScript execution context does compile the code. In the compilation phase it puts the variable firstname
into the memory. As the variable firstname
is in the memory, the console.log
prints undefined
Variable initialization hoisted?
No, JavaScript only hoists declarations, not initializations. For example if we try the followings still we will see the same output:
console.log(firstname); var firstname = 'Joe'; // Output undefined
Example of JavaScript function hoisting
Lets consider following example:
var name = getName(); console.log(name); function getName(){ return 'Joe Smith'; }
Explanation:
JavaScript execution context does compile the code. In the compilation phase it puts the function getName
into the memory. As the function getName
is in the memory, the console.log
prints Joe Smith
Does JavaScript function expression hoisted?
No, function expression is similar to initializating a function into a variable. As initializations are not hoisted in JavaScript, the function expression is also not hoisted. Following is an example of function expression and the right side function will not be hoisted. If we try something like this it will show an error:
var name = getName(); var getName = function(){ return 'Joe Smith'; }
It shows
Error: Uncaught TypeError: getName is not a function