Skip to content

Instantly share code, notes, and snippets.

@ahamed
Created April 30, 2024 18:13
Show Gist options
  • Save ahamed/e2c1227fd8ea0508365cf2bc46ff87b2 to your computer and use it in GitHub Desktop.
Save ahamed/e2c1227fd8ea0508365cf2bc46ff87b2 to your computer and use it in GitHub Desktop.
Hoisting in JavaScript is a behavior where variable and function declarations are moved to the top of their containing scope during the compile phase. This means that regardless of where declarations occur within a scope, they are hoisted to the top. However, it's important to note that only declarations are hoisted, not initializations or assignments. Let me show you an example to illustrate this:
```js
console.log(myVar); // Outputs: undefined
var myVar = 10;
console.log(myVar); // Outputs: 10
```
In this example, even though `myVar` is logged before it's declared and initialized, it doesn't throw an error. This is because the declaration `var myVar;` is hoisted to the top of its scope during the compile phase, resulting in `myVar` being `undefined` when logged before its assignment.
For that reason we could call a function before of its declaration. For example-
```js
sayHello(); // Outputs: Hello!
function sayHello() {
console.log('Hello!');
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment