JavaScript Interview Cheat sheet

JavaScript Interview Cheat sheet

jsimg.png

Introduction

JavaScript is a Single threaded language which runs on a google V8 JavaScript engine.

It was designed as single threaded because to achieve fast execution and to avoid deadlocks(ex. hung state. nothing will execute until its previous statement or function gets executed)

single threaded

JavaScript is a single threaded which means only one statement is executed at a time. It is also called as synchronous programming. The asynchronous programming approach can also be achieved in JavaScript it got very popular in ES6.

Let's see what is synchronous and asynchronous

  • In synchronous programming, the program is executed line by line, one line at a time. Each time a function is called, the program execution waits until that function returns before continuing to the next line of code.

  • In asynchronous programming the program doesn’t wait for the task to complete and can move on to the next task.

Single threaded means it has only one call stack.

what is call stack?

It’s a place or memory component where it keep tracks of executions, if all instructions are executed call stack becomes empty. Whatever is on the top of the call stack runs first. It follows stack data structure LIFO(Last In First Out) . The call stack job is to fill in the instructions and pop an instruction as it gets executed.

callstack.png

How JS Works

whenever a js file is created a Global Execution Context(anonymous function) is created inside call stack. After that it scans code line by line and if any function encounters it adds it to top of the call stack(this functions are also called as execution context) and the variables inside function are added to Scope->Local with values "undefined" in initial for the variables declared as var and variables declared with let and const becomes <uninitialized> . After that variables get values and result is returned execution gets complete and the execution context(function) pops out of the call stack. Call stack becomes empty when all executions are done.

Example of add()

1.png

2.png

3.png

Example by adding sub() function after add() and calling it

4.png

5.png

Hoisting

Definition (in MDN): JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.

In simple words, Hoisting in javascript is a behavior in which function or a variable can be used before declaration

whenever the JS Engine gets our code,a memory component (call stack) is created. JS engine scans the code and stores all the variable and function in this component. The way functions and variables are stored is different :

  1. Functions are stored and made available.
  2. Variables with var keyword are stored with undefined value.
  3. Variables with let and const keyword are stored but not initialized with any value (will result Reference Error) After the memory component is created, the execution phase starts and the code is executed line by line. variables declared with let and const goes into Temporal Dead Zone(TDZ) until they are initialized with some value.

so it’s a better practice to declare in top and using in after to avoid hoisting behavior.

In the given example below variables and functions are used before they are declared. see what they give us as output .

console.log(fullName());  //returns chandrahassan
console.log(city);  //returns undefined
console.log(gender); // returns uncaught reference error :Cannot access 'gender' before initialization
console.log(phoneNo); // this line will not execute

function fullName(){
return "chandrahassan"
}

let phoneNo='123456789';
const gender='M';
var city="Chennai";

hoisting1.png

hoisting2.png

hoisting3.png

hoisting4.png

Scope

Anything which is written inside { } is said to be scope.

Scope refers to the area where an item (such as a function or variable) is visible and accessible to other code.

Mystery of var, let and const variable declaration and its scope

One of the biggest problems with declaring variables with the var keyword is that you can easily overwrite variable declarations In the code below, the fname variable is originally declared as chcodes, and is then overridden to be ch

In a small application, you might not run into this type of problem. But as your codebase becomes larger, you might accidentally overwrite a variable that you did not intend to. Because this behavior does not throw an error, searching for and fixing bugs becomes more difficult.

A keyword called let was introduced in ES6, a major update to JavaScript, to solve this potential issue with the var keyword . So unlike var, when you use let, a variable with the same name can only be declared once.

var-let.png

variables declared using const are read-only. They are a constant value, which means that once a variable is assigned with const, it cannot be reassigned:

Const pic.png

Lexical scope and Scope Chaining

The lexical scope allows a function scope to access the variables from the outer scopes.

A function defined with in a function and that inner function has to print a variable which is not defined in inner function scope . That variable may be defined in outer function or a global variable (global scope). So the inner variable gets value by moving one or more scopes up to the outer functions or from global scope. The mechanism of moving from inner scope -> outer function -> outer function-> global scope is called as scope chaining

function one(){
    let fname="chcodes";
    function two(){
        console.log(fname );
    }
    return two();
}
one();
//output
 chcodes
let fname="globe"; //global scope

function one(){ //##outer scope
    function two(){ //** inner scope
        console.log(fname );
    }  //**
    return two();
} //##
one();
// output
 globe

closure

An inner function defined within a outer function and its referenced inside outer function. As soon as outer function called outer function gets executed and reference to inner function will be created and which can be executed anywhere. a closure is a function that captures variables from its lexical scope. In simple words, the closure remembers the variables from the place where it is defined, no matter where it is executed.

function one(){
    let fname="chcodes";
    function two(){
        console.log(fname );
    }
    return two;
}
let outer=one();
console.log(outer);
//output:
 ƒ two(){
        console.log(fname );
    }
function one(){
    let fname="chcodes";
    function two(){
        console.log(fname );
    }
    return two;
}
let outer=one();
console.log(outer());
//output:
 chcodes

Asynchronous implementation

The asynchronous implementation in Javascript is done through a call stack, call back queue and Web API and event loop. Call stack job as we seen earlier is to check what instruction is at the top of the stack and execute it. If there is an instruction that requires extra time to execute then call stack will pop out that and send it to Web API . Example: setTimeout(), Image need to be loaded, file need to be fetched ,etc.,

The job of event loop is to continuously check if an event occurred, like mouse click or keyboard stroke so that it can send that to call stack. Of course, your mouse click will be given higher priority for execution than an image load.

Once the Web API is done with the execution, it will arrive at the call back queue. call back queue checks whether the call stack is empty. If empty call back queue puts setTimeout() or any instruction into call stack and the instruction is executed.

Web API is a super interesting topic . do a self study on them by clicking the link.

Conclusion

Hope this article will be useful.

THANK YOU! Happy Coding 😊