Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 14, 2022 02:53 pm GMT

Temporal Dead Zone

Hello Everyone, So today I'll talk about the** Temporal dead Zone** in JavaScript.

Temporal Dead Zone(TDZ) is basically refers to the duration between a variable declaration and it's initialization. TDZ occurs when we use const and let for declaring our variables.

Let's look into some of the examples that explains this concept.

This concept of TDZ in JavaScript comes from the concept of hoisting let & const variables.
Like var, let & const are also hoisted but in a different way.

Hoisting example for var:console.log(a); //undefined no errorvar a = 10; 

Here in the above examples explains the concept that no matter your variable after declaration is being initialized or not, it will get a value of undefined during execution if you haven't assigned that variable.

Hoisting example for let variables:console.log(b); let b = 20;

Here in the above example you'll get a reference error, this is because a let variable is being allocated memory in separate space [unlike var variable that is being allocated memory in the global object (i.e; the window object)] which we can't access until we assign some value to that variable. That means let variables can't be accessed until assigned some value to it.

Same goes with the const variables also if you try to access them before initialization it will throw a reference error.

So, the basic idea is let and const variables remains in TDZ until it gets some value assigned to it, once the initialization is done TDZ ends for that specific variable.

Tip: To avoid TDZ always try move all your declaration and initialization part to the top of your program so that before the main logic the execution hits the initialization part.

So, that's it for this time. I hope I made the points clear.
Thank you!!!

Happy Reading!!!


Original Link: https://dev.to/sahiba0915/temporal-dead-zone-1ahe

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To