Home Uncategorized Understanding JavaScript Hoisting

Understanding JavaScript Hoisting

192
0
SHARE

Common definition of Hoisting which you will find on internet :-

Hoisting is JavaScript’s default behaviour of moving declarations (Functions and Variables) to the top

But while executing any javaScript code, moving Functions and Variables to the top is not the only thing which is happening under the hood.

To understand how Hoisting works we need to understand JavaScript’s execution context.

execution context

Whenever any code runs in JavaScript it run inside a execution context. JavaScript engine wrap the current executing code inside a wrapper called execution context.

Base execution context in javaScript is Global execution context.

Execution context is created in two phase

  1. Creation phase
  2. Execution phase
  • Execution context creation phase

During Execution context creation phase javascript engine goes through your code line by line and sets up memory space for all variables and functions.

Initially javascript engine is not sure what is the value of your variable so javascript engine sets it to undefined. initially all variables in javascript are set to undefined. All functions are stored in memory as it is.

  • Execution phase

During Execution phase JavaScript engine execute the code line by line.

Before your code runs line by line, javascript have created memory space for functions and variables so these variables are functions are available for you

LEAVE A REPLY