DEV Community

Sumeet Shedge
Sumeet Shedge

Posted on

Execution Context and Hoisting

In JavaScript, execution context is one of the important topic. With understanding of execution context, you can become better JavaScript developer. let's dive into execution context.

What is Execution Context?

  1. Execution context is like wrapper which helps to running our code better. It's created on function invocation with lots of things.

  2. Execution context wraps our code as well it contain multiple things which is created by JavaScript Engine.

  3. browser created following things for us -

    • window object,
    • this variable,
    • Reference to outer Variable Enviornment,
    • Lexical Enviornment.
  4. Execution context is created within 2 phases - creation phase and code execution phase.

  5. creation phase - in creation phase, we got global object(only for Global execution context), this, lexical Enviornment and Reference to outer Enviornment (except Global Execution context) from JavaScript engine. And JavaScript engine setup memory space for variable and function in creation phase. this setting up space phenomenon called Hoisting.

  6. code execution phase -
    In this phase, JavaScript engine actually run code and execute operations.

b();
console.log(a);

var a = "Hello World";
function b(){
  console.log("b is called");
}
Enter fullscreen mode Exit fullscreen mode

in console window-
b is called
undefined

Hoisting

In JavaScript, when browser run your code and first it create memory space for variable and function in creation phase. when it runs your code, so here they first execute function and then variable.

function is get called properly but variable shows undefined value. because, when browser sets memory for variable, it store with undefined value.

Top comments (0)