JavaScript variables can be declared after they have been used.
Before jumping into examples and how hoisting effects programming, you must know what hoisting means. Hoisting is JavaScript's default behavior to moving all declarations to the top of the current scope, whether that is the script or the function you are working within. Functions can also be hoisted, but there are two types of functions;
- Function declarations
- Function expressions
Function declarations can be hoisted to the top, here is an example
hoist(); // Output: "A hoisted function'"
function hoist() {
console.log('A hoisted function');
};
A function expression cannot be hoisted to the top
expression(); //Output: "TypeError: expression is not a
function
var expression = function() {
console.log('Will this work?');
};
Function definition hoisting only occurs for function declarations, not function expressions.
Var initialization can be hoisted and let and const are hoisted to the top of the block, but not initialized The code knows of the variables existence, but it CANNOT be used until it has been declared.
Var:
b = 20; // Assigns 20 to b
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element
var b; // Declares b
Let:
carName = "Volvo";
let carName;
//ReferenceError
Top comments (0)