Hoisting in JavaScript

Hoisting is a phenomenon in JavaScript, in which we can access variables and functions without any error before their initialization. This happens because even before the code starts executing, memory is allocated to variables and functions.

JavaScript is synchronous and single threaded language where everything happens inside a Global Execution Context. When we run a JS program, an execution context is created, which is further divided into two phases:

  • Memory Allocation Phase (Variable Environment)
  • Code Execution Phase (Thread of Execution)
In the first phase, the entire program is skimmed line by line and memory is allocated to functions and variables. In case of variables, undefined is stored as a placeholder and in case of functions, the whole code of function is stored.

In the second phase, the code is actually executed line by line. Undefined keyword is now replaced by actual values of variables. When there is a function invocation, a entirely new execution context is created which has further two components. When return keyword is encountered, it just returns all the controls to the global execution context where the function was first invoked. After complete execution of function, the execution context related to the instance of function is deleted. Then, the next line is executed.

The creation/deletion of execution context is controlled by Call Stack in JavaScript, with Global Execution Context being pushed first and the last to be popped out.

So when, variables are accessed before their initialization (second phase), simply undefined is printed. In case, if the variable is deleted later, Uncaught Reference Error is thrown saying variable was not defined. There is a huge difference between not defined and undefined.

When functions are accessed before their initialization (second phase), their output is printed as in first phase their entire code is stored.

For more information you can refer here.

Comments

Popular posts from this blog

JavaScript Engine

Agile Software Development

Make Your First Pull Request!