JavaScript Variable Lifecycle Explained
Tags: javascript, var, let, const
Published: 2021-01-27 12:19:22

Here I wrote my self note regarding JavaScript variable lifecycle. I hope this will make a quick recap to you.

Let’s consider below code block.

```javascript
sayMyName('Rasika')

function sayMyName(userName) {
console.log(`Hello ${userName}`);
}
```

Simply this function identifier hoisted. That means every identifier created at the beginning of its scope. But there is another thing. Have you ever thought that however that `sayMyName` got the value when the relevant scope starts to run. 

This is because of `function hoisting`. Whenever function’s name identifier registered on the top of the scope that it belongs, it will also initialize that moment. 

>Note: This will happen if you declare a function with function declaration. Not for the function assign to variable.

>If you try below code you will get `ReferenceError` that saying `Cannot access ‘sayMyName’ before initialization` 

```javascript
sayMyName();
const sayMyName = (userName) => {
console.log(`Hello ${userName}`);
};
```
If you use `var` instead `const` you will get a `TypeError`.

```javascript
TypeError: sayMyName is not a function
```
Moreover, we are considering `var` scenario in here. Okay, with that error `sayMyName` have a value but it is not a function reference. That is what can we get from the error message.

Whenever we declared with `function` it will be hoisted and initialize the function value to itself.

```javascript
function sayMyName(userName) { ... }
```

But…, if we define a `var` variable and assign an `function` expression it will hoised and assign `undefined` to the variable value. Until in the runtime that assignment happened, it will not have the function reference. (like below code block)

```javascript
var sayMyname = function sayMyName(userName) { ... }
```

>**Hoisting rule is, hoist the function declaration first, the hoist variables.**

As the example consider this example.

```javascript
myName = "Rasika";
sayMyName()


function sayMyName() {
console.log(`My name is ${myName}`);
}

var myName;
```

Basically, it will execute like this.

```javascript
function sayMyName() {
console.log(`My name is ${myName}`);
}
var myName;
myName = "Rasika";
sayMyName()
```

But if you use `let` or `const` this will not run the code. It will throw `SyntaxError`.

Consider the below example.

```javascript
const myFavoriteFruit = "Mango";

console.log(myFavoriteFruit);

myFavoriteFruit = "Ba na na"
```
In here first, you will get the console output and then get the `TypeError`. NOT a `SyntaxError`.

Also in `for` loop, the inner variable will declare once per scope instance. Not a re-declaration.

```javascript
for (let i = 0, i < 5, i++){
// in here i will be declare in five separate scope instances 
}
```

Also, this is works with `for..in` and `for..of` same like this.

But if you use `const` in `for` loop it will fail after the first iteration.
```javascript
for (const i =0; i < 5 , i++) { // will give an error after 1st iteration }
```
But const will work with `for..in` and `for..of`.

### Temporal Dead Zone

Consider below code block.

```javascript
console.log(myFavoriteFruit);

let myFavoriteFruit = "Mango";
```
This will gives below error.

```javascript
ReferenceError: Cannot access 'myFavoriteFruit' before initialization
```
So we can come to the conclusion that we cannot use a variable at any time prior to its initialization that if we are using `let` or `const`. Basically, this is referring to as **Temporal Dead Zone (TDZ)**. 

> Make sure that let and const also, hoist the variable.

But it will not auto-initialize. It is basically auto-register the variable top of the scope.

We can avoid this TDZ by defining variables top of the scope.

Reference:
[The (Not So) Secret Lifecycle of Variables](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch5.md) I highly encourage you to go and check this article.

[MDN - var](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)

[MDN - let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)

[MDN - const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)

If you have anything to ask regarding this please leave a comment here. Also, I wrote this according to my understanding. So if any point is wrong, don’t hesitate to correct me. I really appreciate you.

That’s for today friends. See you soon. Thank you

Cover [image credit](https://www.pexels.com/photo/person-under-delicate-arch-at-night-33688/)