Javascript Interview Preparation Cheatsheet.

Javascript Interview Preparation Cheatsheet.

Javascript in-depth Concepts for Interview Preparation.

While preparing for interview questions for Javascript, you need to clear these basic concepts because these concepts will help you to understand how javascript works. Whenever you get tricky questions in the interview, you can easily give an answer with a proper explanation.

In part one of the Javascript Interview preparation, we will understand

  • Call Stack
  • Execution Context
  • Why JS is single threaded Language that can be non Blocking.
  • Scope
  • Hoisting

Call Stack

Stack is a linear Data Structure that is similar to an array, except that we cannot access the element with index position and we can only insert (push data) or delete data (pop data) from the top. It follows LIFO(Last In First Out), so whenever we add an element is directly stored on top of the stack and whenever we delete elements it's deleted from the top.

The below example will help you to visualize what a stack looks like and how push and pop operation happens.

Call Stack.png

In programming, the stack (Call stack) is used to store the order of function calls. So that we can store the latest function call at the top, once the function is executed, the last executed function can be removed from the stack.

The call stack is basically a collection of multiple execution contexts where your code runs.\

Have you ever heard of stack overflow, this stack has limited memory to store data and when the stack is filled to the top then it's called stack overflow. (You can do stack overflow with simple recursion)

Execution Context

function getMessage(){
  return "Hi Hitesh"
}
function sayHello(){
return getMessage()
}

Javascript Engine sees these brackets and says "Oh I need to execute this function, let me create one execution context" As you can see below image that is an Execution Context.

Call Stack (1).png

But there is a base execution context called as Global Execution Context. So whenever code is running there will always be a Global Execution Context (GEC).

Global Execution Context gives us 2 things one is a Global object (which is a window object) and another is this keyword.

When an execution context is formed there are 2 phases

  1. Creation Phase
  2. Execution Phase

Creation Phase

The creation Phase happens first and in this phase, we get a global object, this keyword, and arguments. We also get a Local environment to store the values. All the assigned values in this function are stored in the local environment. Hoisting also happens in that local env.

Execution Phase

In the execution phase, we just run the code line by line.

Call Stack (3).png

Why JS is a single-threaded Language that can be non Blocking?

Javascript is a single-threaded language which means it has only one call stack and it can only execute only one program at a time. Why single-threaded, it's easy and has no compilations.

So I have heard that JS can do asynchronous programming so how it can be single-threaded? Let's take an example and see how JS do asynchronous programming

console.log("1");
setTimeout(() => {
  console.log("2");
}, 2000)
cosole.log("3")

setTimeout is given us by Web APIs, it's technically not a part of JS. The result would be 1 3 2 setTimeout wait for 2 sec and then it printed. but if js is synchronous it should give 1 2 3 but no because of asynchronous.

Behind the Scenes

Call Stack (6).png

  1. Call Stack is run and GEC is created and on top of that, It executes console.log("1") and removes the stack.
  2. After that setTimeout function is created and it says Oh! this is given by the Web APIs, let me send it to Web APIs Web APIs: I've set timeout with me and I will execute it after 2 seconds
  3. console.log("3") is executed and it prints the 3 value.

Call Stack (7).png

  1. When 2 sec is over set timeout will execute the callback function and say Oh! its console.log("2")
  2. Now Web APIs will send this callback queue saying there's a callback please provide.

    Callback queue is a queue where it keeps track of all callbacks. Now there is something called an event loop. The event loop check's if the call stack is empty then it pushes the callback to run in the stack. This is basically its job.

  3. Event Loop will check whether the call stack is empty or not. If empty then it will push the callback from the callback queue in the call stack.

Scope

The scope means the current context of execution in the call stack in which values and expressions are visible.

the scope in which a variable can be accessed: Simplistically

There are three main types of Scope.

  1. Global Scope
  2. Function Scope OR Local Scope
  3. Block Scope

Global Scope

The variable that has been declared in the root of the file is called global scope.The default scope for running all scripts is in Global Scope.

var name = "Hitesh";
function myName(){
  return name;
}
console.log(myName());

Function Scope

So, whenever a function is created it creates an execution context, and execution context also gives us a local variable environment. A function creates a scope and stores the variable in the local env exclusively so that it can't be accessed outside the function. We can only access the variables inside the function inside it. We can't access it outside the function because they're within the function scope.

function myName(){
  var name = "Hitesh";
  return name;
}
console.log(myName());

Block Scope

Block is the scope that is created inside the curly brackets { }. Javascript follows function scope and didn't actually have block scope until Es6 was introduced. We can only acquire block scope with the help of let and const. If we use var it won't create a block.

if{
  var name = "Hitesh";
}
console.log(name); // Hitesh will be printed out.

So to create a block scope we need let and const.

if{
  let name="Hitesh";
}
console.log(name); // this will give us a reference error because we can't access it outside the scope.

Scope chaining

To understand scope chaining let's take a simple example.

Kid.png

So in this typical world, there are kids, middle guy, and big guy as you can see in the above image. So a kid wants a popsicle, so if he has a popsicle then it's okay he can eat it, but if he doesn't have it he can simply ask the middle guy for a popsicle and if they don't have it he can ask from the big guy. If a middle guy wants a popsicle, if he has a popsicle then it's okay he can have it, but if he doesn't have he can ask for the popsicle from his grandparent. But he never asks for the popsicle from the kid. This is the moral rule that we imply. Just like that if the Big guy wants a popsicle, if he has it he can have but he can never ask for the middle guy or kid for the popsicle.

Just like this happens in Scope too. Hope you understand the scope chaining.

Hoisting

console.log(name);
var name = "Hitesh"; // output -> undefined

Why undefined? Shouldn't it say reference error? It's because of Hoisting. During the creation phase, JS sees this variable and allocates memory, and keeps its value undefined. That's why we got undefined.

Definition: Hoisting is a JavaScript mechanism where the JavaScript interpreter moves all variable and function declarations to the top of the current scope before the code execution starts. Behind the scene, it just allocates memory and keeps it undefined. But for functions, it's a different case.

console.log(name);
let name = "Hitesh"; // output -> reference error

But why, do we get an error shouldn't we be getting undefined? Or let and const are not hoisted at all?

Let and const are hoisted too but as you can in the below image they are hoisted in a different file not in a global file in the case of var it is hoisted in a global file and we have access to it, that's why we get undefined in var.

var.PNG

One of the advantages of hoisting is that it lets you use a function before you declare it in your code.

myName();
function myName(){
  console.log("Hitesh");
}

Function declarations are completely hoisted. It means all things in curly brackets of function are stored
while hoisting. Because of this, it can access the function before it's been executed.

We have completely studied the important topics for Javascript interview preparation. Understanding these concepts will help you to know more about JS.