JavaScript (Part-1)

JavaScript (Part-1)

Topics Covered : How JavaScript executes, Hoisting in JS, Undefined vs not defined

JavaScript is a synchronous, single-threaded language.

How JavaScript executes.

"Everything in JavaScript happens inside an Execution context"

When we run JavaScript code a Global Execution context is created where all the code runs. This Global execution context is consist of two phases.

  1. Memory creation / Creation Phase

    In this our JavaScript engine goes through each line and declare each variable in Global object and put undefined in it whereas each function is also declared and it points to whole function code.

  2. Execution Phase

    In this phase JavaScript engine again goes through each line and initialize variables with its value and also executes the code line by line. When a function is invoked JavaScript engine makes a new execution context for the function and again repeats the Creations and execution phase for that function and once the function execution is completed the function execution context gets destroyed or pops out from the call stack.

    There is a call stack present, it contains all the execution context including GCE.

    When a function is invoked its execution context gets pushed into call stack.

Hoisting

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables, classes, or imports to the top of their scope, prior to execution of the code. In other words a variable can be used before it has been declared. JavaScript only hoists declarations, not initializations.

getName()

console.log(x)

var x=9;
function getName(){
    console.log("Hello Aakash")
    }

// output : Hello Aakash
//          undefined

This happens because in Creation phase all the variables get declared and set undefined to it.

If we define function using arrow function then the above give error as in this way getName behaves as a variable and set it to undefined.

const getName = () => {
        console.log("Hello Aakash")
    }

At the global level this keyword represents window or global object. Anything which is not inside a function is present in global space.

Not Defined and Undefined

Undefined comes when we try to access a variable which is defined and initialized later in the code.

Not defined comes into play when we try to access a variable which is never declared and initialized in the code.