Hoisting - TristanVarewijck/Block-Tech GitHub Wiki
What is hoisting?
"Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function)."
- In JavaScript, a variable can be declared after it has been used.
- In other words; a variable can be used before it has been declared to a const, let or var.
Code example:
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element
var x; // Declare x
So x
has a value of 5 but it hasn't been declared before it was used, the declaration became after that but it still worked...
This is called hoisting x is declared after it has been used.
The same concept can also be used this way
var x
x = 15
function whatIsX(){
console.log(x)
}
whatIsX() // 15
You can make a variabel without a value... and you can assign it later in a global or function scope.
Remember this!
- Variable hoisting means the JavaScript engine moves the variable declarations to the top of the script!
A Summary
- JavaScript hoisting occurs during the creation phase of the execution context that moves the variable and function declarations to the top of the script.
- The JavaScript engine hoists the variables declared using the let keyword, but it doesn’t initialize them as the variables declared with the var keyword.
- Function expressions and arrow functions aren’t hoisted.
Resource
- JavaScript Hoisting | W3Schools
- JavaScript Hoisting | JavaScript Tutorial