Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables, or classes to the top of their scope, prior to the execution of the code.
Hoisting enables functions to be safely used in code before they are declared.
Note: The term hoisting is not used in any normative specification prose prior to ECMAScript® 2015 Language Specification. Hoisting was created as a general way of thinking about how execution contexts (specifically the creation and execution phases) work in JavaScript.
Function Hoisting
One of the advantages of hoisting is that it lets you use a function before it is declared in the script.
catName('Tiger');
function catName(name) {
console.log('My cat\'s name is ' + name);
}
Running this script will produce the output “My cat's name is Tiger
”, despite invoking catName
before declaration.
Variable Hoisting
Variables are hoisted as well, but only declarations are hoisted, not initializations! Initialization does not happen until the associated line of code is interpreted.
Until the variable is initialized, the variable has its default state (undefined
for variables declared with var
, and uninitialized otherwise).
Note: Conceptually, variable hoisting is often presented as the interpreter splitting variable declaration and initialization, and moving the declaration to the top of the applicable scope.
Further reading: