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 code.
JavaScript variable hoisting
Lets consider following example:
console.log(firstname); // undefined var firstname; firstname = 'Joe';
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
Is 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
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 the initialization of 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(); console.log(name); var getName = function(){ return 'Joe Smith'; }
// Output Error: Uncaught TypeError: getName is not a function