# 15. MEDIUM | Hoisting in Javascript

* * *

## What is Hoisting?

Hoisting refers to the process whereby the **<mark class="bg-yellow-200 dark:bg-yellow-500/30">interpreter appears to move </mark>** `var` **<mark class="bg-yellow-200 dark:bg-yellow-500/30"> variables, function declarations and class declarations to the top of the code before execution</mark>**.

`var` variables, function declarations and class declarations can thus be referenced before they are declared in javascript.

```javascript
console.log(username); // Output: undefined

sayHi(); // Output: Hi, Shubham!

var username = 'shubham';

function sayHi() {
    console.log("Hi, Shubham!")
}
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><code>let</code><mark class="bg-yellow-200 dark:bg-yellow-500/30"> and </mark><code>const</code><mark class="bg-yellow-200 dark:bg-yellow-500/30"> variables, function expressions and class expressions are not hoisted.</mark> If we try to refer them before initialization, we will get <code>ReferenceError</code>.</div>
</div>

```javascript
// let and const variables

console.log(username); // throws ReferenceError [Reason:- let in TDZ]
console.log(age); // throws ReferenceError [Reason:- const in TDZ]

let username = 'shubham';
const age = 25;
```

```javascript
// function expressions

func1(); // Error [Reason:- undefined()]
func2(); // Error [Reason:- let in TDZ]
func3(); // Error [Reason:- const in TDZ]

var func1 = function() {
    console.log('I am func1.')
};

let func2 = function() {
    console.log('I am func2.')
};

const func3 = function() {
    console.log('I am func3.')
};
```

### Logic behind hoisting behaviors?

Javascript code is executed in 2 phases viz. first, memory creation phase and second, code execution phase.

* * *

Happy reading!
