JavaScript Hoisting intro
Hoisting is where a variable and function declaration is moved to the top of its scope during compilation. This means that variables and functions can be used before they are declared in the code. You should know that since the declaration is hoisted but not the initialization of the variable the variable will be undefined. A function will be hoisted differently and will be available.
Here are some quick examples.
Variable Hoisting
console.log(aVariable); // undefined, not ReferenceError
var aVariable = 5;
console.log(aVariable); // 5
In this example:
- At first
console.log
printsundefined
because the declaration ofaVariable
has been hoisted but int initialized. - The second
console.log
prints5
becauseaVariable
has been initialized.
Example of Function Hoisting
console.log(helloWorld()); // Outputs: "Hello, World!"
function helloWorld() {
return "Hello, World!";
}
In this example:
- The call to
helloWorld()
works even though it appears before the function declaration in the code because the entire function declaration has been hoisted.