Hoisting and TDZ

Hoisting and TDZ

If you are new to javascript language and don't know what hoisting is don't worry this blog will help you understand what Hoisting and Tdz are.

ยท

4 min read

Before getting to hoisting and TDZ let's have a look at a simple Example:

var age = 30;
function getName(){
 console.log("Bruce Wayne");
}

getName();
console.log(age);

There's nothing new in this example just a variable (age) and a function (getName). if we try to run this code in the browser we get the following output.

Output: image.png

Now let's make some changes to the above code. And then run it to see the output.

getName();
console.log(age);

var age = 30;

function getName(){
 console.log("Bruce Wayne");
}

Output: image.png

This time we get different output as compared to the previous one. Here when we try to call the function getName() we get the same output but when we try to console the value of variable age we get the output as undefined. You may wonder ๐Ÿค” why even though the code is same but this time there is a twist. Here we are trying to access the variable before it is even declared and initialized. Well here comes the concept of Hoisting. But first, we need to understand What is execution context in javascript and how it works?. Don't worry this blog has a brief explanation of these concepts.

Execution Context

Think of the Execution context as a box that has two components. First, is the Memory Component also known as the variable environment. Here all the functions and variables are stored in the form of a key: value pair. The Second Component of the execution context is the code component also known as the Thread of Execution. In this component, all the lines of code are executed one at a time as "javascript is synchronous single-threaded language".

How Execution Context Works

Whenever a javascript program runs a global execution context is created. This execution context is created in two phases:

  1. Creation Phase
  2. Execution Phase

Creation Phase In the Creation Phase, Javascript skims through the whole program and reserves memory for all the functions and variables. The variables are assigned with the value undefined whereas in the case of functions the whole code inside the function is stored.

Execution Phase In this phase, the javascript goes through each line of code one by one. Then variables that are reserved in the first phase are assigned the values that are mentioned in the code. And also performs operations if any are present in the code.

Let's Understand this better by taking the first Example:

image.png

image.png

Added Debugger to the first line of code so this is just the Creation Phase. You see how age is given the value undefined and the function is stored. Now when we click on step over next function call the variable a is assigned the value 30. image.png

Now let's get back to

What is Hoisting?

According to MDN, JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables, or classes to the top of their scope, prior to execution of the code.

Hoisting allows functions to be safely used in code before they are declared. Variable and class declarations are also hoisted, so they too can be referenced before they are declared but doing so can lead to unexpected errors, and is not generally recommended. This is the reason why in example two we did not get any error on calling the function before we declared it but got undefined when we tried to print the value of variable age.

Here is a point to remember that javascript only hoists declarations, not initializations! This means that initialization doesn't happen until the associated line of code is executed, even if the variable was originally initialized then declared, or declared and initialized in the same line.

var hoisting

console.log(num);
var num = 8;
console.log(num);

image.png

If we forget the declaration altogether (and only initialize the value) the variable isn't hoisted. Trying to read the variable before it is initialized results in ReferenceError exception.

console.log(num);
num = 8 ;

image.png

let and const hoisting

Variables declared with let and const are also hoisted but, unlike var, are not initialized with a default value. An exception will be thrown if a variable declared with let or const is read before it is initialized.

console.log(num);
console.log(num2);
const num = 8;
let num2 = 6;

image.png

if you want to know more differences between var, let, and const do check out here.

TDZ

A temporal dead zone (TDZ) is the area of a block where a variable is inaccessible until the moment the computer completely initializes it with a value.

  • A block is a pair of braces ({...}) used to group multiple statements.
  • Initialization occurs when you assign an initial value to a variable.

Example

let x = "outer value";

(function() {
  // Start TDZ for x.
  console.log(x);
  let x = "inner value"; // Declaration ends TDZ for x.
}());

image.png

How to avoid issues TDZ causes

Simply define your let and const variables at the top of your scope.

ย