JavaScript 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 execution of the code.
Hoisting allows functions to be safely used in code before they are declared.
Variable and class declarations are also hoisted, so they too can be referenced before they are declared. Note that doing so can lead to unexpected errors, and is not generally recommended.
Function hoisting
One of the advantages of hoisting is that it lets you use a function before you declare it in your code.
catName("Tiger");
function catName(name) {
console.log(`My cat's name is ${name}`);
} /* The result of the code above is: "My cat's name is Tiger" */
Without hoisting you would have to write the same code like this:
function catName(name) {
console.log(`My cat's name is ${name}`);
} catName("Tiger"); /* The result of the code above is the same: "My cat's name is Tiger" *
Variable hoisting
Hoisting works with variables too, so you can use a variable in code before it is declared and/or initialized.
However, JavaScript only hoists declarations, not initializations! This means that initialization doesn't happen until the associated line of code is executed, even if the variable was originally initialized then declared, or declared and initialized in the same line.
Until that point in the execution is reached the variable has its default initialization (undefined for a variable declared using var, otherwise uninitialized).
Top comments (1)
Use Book "You dont know Js" That might help for learning this hoisting concept :)
Some comments have been hidden by the post's author - find out more