JavaScript Interview Cheatsheet

JavaScript Interview Cheatsheet

Execution context scope, Hoisting, Call stack, Thread in JavaScript

This article will briefly explain Execution context scope, hoisting, call stack and thread in JavaScript.

Execution context scope

Execution context or EC is an environment in which JavaScipt code is executed. Here, the value of this, variable and functions are stored. Execution context is of two types in JavaScript, they are

Global Execution Context or GEC

When the JavaScript loads in the browser it starts executing in GEC. All the global code executes (which is not written inside function or object) in GEC. As we know JavaScript engine is single-threaded so there will be only one Global Execution Context. We can also say that JavaScript has a single Global Execution Context, single Thread and single Process.

Functional Execution Context or FEC

If there is any function call JavaScript engine creates a Functional Execution Context or FEC. FEC can be more than one because there may be more than one function and each function has one FEC.

Hoisting

Hoisting in JavaScript is a special feature in which a function or a variable can be used before declaration. Hoisting is not performed in Java, C or C++ and some other programming language.

Variable hoisting

only the variable declared using 'var' keyword is purely hoisted, not 'let' or 'const'. Variable declared using 'let' or 'const' keyword is hoisted but not accessible until it is assigned a value because the variable goes to the temporal dead zone.

num = 15;
console.log(num);
var num;
// output: 15

but if we declare a variable and not initialized it then it will not be hoisted

console.log(num)
var num;
// output: undefined

Function hoisting

A function is also hoisted which means that we can call a function before it is declared.

getName();
function getName(){
  console.log("Shams");
}
// output: Shams

On the other hand, the function used as the expression is not hoisted. If we try to do so it will throw an error

getName();
let getName = function(){
  console.log("Shams");
}
// output: Uncaught ReferenceError: getName is not defined

Call stack

We a function is called or invoked, this is done by call stack. A call stack is synchronous so so one function is called at a time. The JavaScript call stack is an example of a stack data structure so every time function is called it is added to the stack.

Thread

A thread is light weight process. A thread in programming language refers to the execution of running multiple tasks or programs at the same time. JavaScript is a single-threaded language unlike other programming languages like Java.