Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for JavaScript Variable Lifecycle Explained
Rasika Gayan Gunarathna
Rasika Gayan Gunarathna

Posted on • Originally published atrasikag.com

     

JavaScript Variable Lifecycle Explained

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.

sayMyName('Rasika')functionsayMyName(userName){console.log(`Hello${userName}`);}
Enter fullscreen modeExit fullscreen mode

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 thatsayMyName got the value when the relevant scope starts to run.

This is because offunction 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 getReferenceError that sayingCannot access ‘sayMyName’ before initialization

sayMyName();constsayMyName=(userName)=>{console.log(`Hello${userName}`);};
Enter fullscreen modeExit fullscreen mode

If you usevar insteadconst you will get aTypeError.

TypeError:sayMyNameisnotafunction
Enter fullscreen modeExit fullscreen mode

Moreover, we are consideringvar scenario in here. Okay, with that errorsayMyName have a value but it is not a function reference. That is what can we get from the error message.

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

functionsayMyName(userName){...}
Enter fullscreen modeExit fullscreen mode

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

varsayMyname=functionsayMyName(userName){...}
Enter fullscreen modeExit fullscreen mode

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

As the example consider this example.

myName="Rasika";sayMyName()functionsayMyName(){console.log(`My name is${myName}`);}varmyName;
Enter fullscreen modeExit fullscreen mode

Basically, it will execute like this.

functionsayMyName(){console.log(`My name is${myName}`);}varmyName;myName="Rasika";sayMyName()
Enter fullscreen modeExit fullscreen mode

But if you uselet orconst this will not run the code. It will throwSyntaxError.

Consider the below example.

constmyFavoriteFruit="Mango";console.log(myFavoriteFruit);myFavoriteFruit="Ba na na"
Enter fullscreen modeExit fullscreen mode

In here first, you will get the console output and then get theTypeError. NOT aSyntaxError.

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

for(leti=0,i<5,i++){// in here i will be declare in five separate scope instances}
Enter fullscreen modeExit fullscreen mode

Also, this is works withfor..in andfor..of same like this.

But if you useconst infor loop it will fail after the first iteration.

for(consti=0;i<5,i++){// will give an error after 1st iteration }
Enter fullscreen modeExit fullscreen mode

But const will work withfor..in andfor..of.

Temporal Dead Zone

Consider below code block.

console.log(myFavoriteFruit);letmyFavoriteFruit="Mango";
Enter fullscreen modeExit fullscreen mode

This will gives below error.

ReferenceError:Cannotaccess'myFavoriteFruit'beforeinitialization
Enter fullscreen modeExit fullscreen mode

So we can come to the conclusion that we cannot use a variable at any time prior to its initialization that if we are usinglet orconst. Basically, this is referring to asTemporal 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 I highly encourage you to go and check this article.

MDN - var

MDN - let

MDN - 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

Coverimage credit

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Full-stack web developer. Life-long learner. Skater.
  • Location
    Singapore
  • Work
    Software Engineer
  • Joined

More fromRasika Gayan Gunarathna

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp