Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their respective scopes during the compilation phase, before the code is executed. This means that you can use a variable or function before it is declared in your code. However, only the declarations are hoisted, not the actual assignments or function expressions.
Here's an example of hoisting with variable and function declarations:
console.log(x); // Output: undefined
var x = 5;
foo(); // Output: "Hello, World!"
function foo() {
console.log("Hello, World!");
}
In the above code, the console.log statement for the variable x outputs undefined. This is because the declaration of the variable is hoisted to the top of the scope, but the assignment happens later in the code. So, at the time of the console.log statement, x has been declared but has not yet been assigned a value.
Similarly, the foo() function declaration is hoisted to the top of the scope, so you can call it before it appears in the code. This will output "Hello, World!" to the console.
It's important to note that only function declarations and variable declarations using var are hoisted. Other types of variable declarations, such as those using let or const, are not hoisted. Additionally, function expressions (such as const foo = function() {...}) are also not hoisted.
Top comments (0)