DEV Community


Posted on


Hoisting and Temporal Dead Zone

Hoisting is effectively the result of JavaScript Engine's 2 phase Execution of the program(

What is hoisting?

When variables are encountered during the program run, during the first pass they are given space in memory and initialized with undefined

The variables are updated with their actual values only when the thread of execution reaches the line of code, where they are initialized.

So effectively during hoisting we feel as if the variables are "hoisted" to the top, but actually during the first pass, all variables are assigned undefined and stored in memory.

What is hoisted?

Although all three types of declaration, let, const and var are hoisted, var behaves differently from let and const. var declarations are initialized with undefined, but let and const are not initialized with a default value, instead an exception will be thrown when we try to access let and const before its initialization from the thread of execution inside from the source file.

// The first pass occurs and thread of execution starts from here
// Here vx stores undefined
var dev = "dev"    // vx now stores "dev"
Enter fullscreen mode Exit fullscreen mode
// The first pass is over
// Here the Engine knows about cx and lx, but cannot assign a value to them
const cx = 'dev' // now cx has its value as 'dev'
const lx = 'dev' // now lx has its value as 'dev'
Enter fullscreen mode Exit fullscreen mode

Temporal Dead Zone

When trying to access let and const variables, before its initialization from the source file's thread of execution, will result in a reference error. The variable is in the Temporal Dead Zone from the start of its initialization in the first pass, till the thread of execution assigns some value to it. Here JavaScript knows that a variable exists, but doesn't know what it data/value it holds

// Line 1, here Engine knows about x, but not its value, start of temporal dead zone
let x = 'dev'
// After assigning x some value, temporal dead zone is over, as its declaration is complete
Enter fullscreen mode Exit fullscreen mode

Common Confusion

  1. undefined refers to something that doesn't exist yet, or doesn't exist anymore
  2. null refers to an empty value
  3. not defined refers to an exception in which JavaScript Engine doesn't know about the identifier requested
  4. reference error refers to an exception in which, let or const is accessed before its declaration is complete

To get a video tutorial on the concept


Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await