Explain hoisting in Javascript

Hoisting in JavaScript is a mechanism 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 regardless of where variables and functions are declared in the code, they are treated as if they were declared at the top of their scope.

Variable hoisting:

When a variable is declared using the var keyword, it is hoisted to the top of its scope and initialized with a value of undefined. However, the assignment of the actual value is not hoisted, only the declaration.

For example:

console.log(myVariable); // Output: undefined
var myVariable = 10;
console.log(myVariable); // Output: 10

Function hoisting:

Function declarations are also hoisted to the top of their scope, allowing them to be called before they are defined in the code.

For example:

myFunction(); // Output: "Hello, World!"
function myFunction() {
console.log("Hello, World!");
}

However, it’s important to note that function expressions (functions assigned to variables) are not hoisted. Only the variable declaration is hoisted, not the function assignment.

For example:

myFunction(); // Output: Uncaught TypeError: myFunction is not a function
var myFunction = function() {
console.log("Hello, World!");
};

In HTML format, the code examples would look like this:

Variable hoisting:

<script>
console.log(myVariable); // Output: undefined
var myVariable = 10;
console.log(myVariable); // Output: 10
</script>

Function hoisting:

<script>
myFunction(); // Output: "Hello, World!"
function myFunction() {
console.log("Hello, World!");
}
</script>

Function expression hoisting:

<script>
myFunction(); // Output: Uncaught TypeError: myFunction is not a function
var myFunction = function() {
console.log("Hello, World!");
};
</script>

In summary, hoisting in JavaScript allows variables and function declarations to be moved to the top of their respective scopes during compilation, enabling them to be accessed before they are defined in the code. However, it’s important to understand the differences between variable and function declarations, as well as function expressions, to avoid unexpected behavior.