What is hoisting in JavaScript?

Hoisting is a behavior in JavaScript where variable declarations and function declarations are moved to the top of their respective scopes during the compilation phase, before the code is executed. This means that variables and functions can be used before they are declared in the code.

For example, if you declare a variable at the bottom of a function, but use it at the top, hoisting will move the declaration to the top of the function:

javascript
Copy code
function myFunction() {
console.log(x); // Output: undefined
var x = 1;
}
In the example above, even though x is used before it is declared, hoisting moves the declaration to the top of the function, so x is defined, but its value is undefined at the point where it is used.

However, only the declaration is hoisted, not the initialization. So if you try to access a variable before it is declared and initialized, you will get a ReferenceError:

javascript
Copy code
function myFunction() {
console.log(x); // Output: ReferenceError: x is not defined
var x = 1;
}
Hoisting also applies to function declarations, which means you can use a function before it is declared:

scss
Copy code
myFunction(); // Output: "Hello World!"

function myFunction() {
console.log("Hello World!");
}
In this example, myFunction is called before it is declared, but hoisting moves the declaration to the top of the script, so it works as expected.