Hoisting in JavaScript:

Hoisting in JavaScript:

"Demystifying Hoisting: Unraveling the Inner Workings of JavaScript"

Table of contents

No heading

No headings in the article.

Definition:

The javascript mechanism in which variables and function declarations are moved to the top of their scope before execution of the code is called hoisting.

Behind the scenes of hoisting in javascript:

Execution context: In layman's terms, an execution context refers to an abstract environment where the javascript code gets executed. This environment consists of what are the variables, functions, and objects in its scope, the memory allocated and the line-by-line execution of the code. Everything that happens in javascript is inside the execution context.
The execution context created on the first time parsing the code is called global execution context(GEC), and the ones after it is called local/functional execution context(FEC).

Creation of Execution Context: Behind the scenes, javascript creates an execution context(global). This execution context has two phases: Creation and Execution

  1. Creation Phase:
  • JavaScript first scans the code, registers the variables in the scope, and allocates the memory to all the variables and function declarations.

  • If it encounters a variable, it is given the value undefined, and if it encounters the function, then the value function code itself, and a new execution context is created.

  1. Execution Phase:
  • After the creation phase, the JS engine executes the code line by line and assigns the actual value to the variables in the memory instead of undefined.
    *Whenever the JS engine finds the function execution a new execution context(functional execution context) is created for that function. And again this execution context goes through two phases.

\=> Once the execution context is finished executing, the execution context gets deleted from the call stack. => The work of call-stack is to contain execution contexts and to append once the code starts executing and pop them out once the code finished executing.

Call Stack is aka. Execution Context Stack, Program Stack, Control Stack, Runtime Stack, etc.

Takeaways: *JavaScript doesn't allow function expressions hoisting. *JavaScript doesn't allow arrow function hoisting.