hoisting in js in javascript

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their respective scopes before code execution. This means that you can use these variables or functions before they are declared in your code. However, only the declarations are hoisted, not the initializations.

Let's see an example of how hoisting works with variables:

index.tsx
console.log(myVariable);  // Output: undefined
var myVariable = 10;
68 chars
3 lines

In the above code, even though myVariable is declared after the console.log statement, the declaration is hoisted to the top of the scope and the output will be "undefined".

A similar example with a function:

index.tsx
myFunction();  // Output: "Hello World!"

function myFunction() {
  console.log("Hello World!");
}
99 chars
6 lines

Again, the function declaration is hoisted to the top of the scope and can be called before it is defined.

It's important to note that only the declarations are hoisted, not the initializations. For example:

index.tsx
console.log(myVariable);  // Output: "ReferenceError: myVariable is not defined"
let myVariable = 10;
102 chars
3 lines

In this case, if you use let to declare myVariable, it is not hoisted to the top of the scope and trying to use it before its declaration will result in a "ReferenceError".

gistlibby LogSnag