Javascript Interview Preparation Cheatsheet

Javascript Interview Preparation Cheatsheet

Topics to be covered in this article

  • Scope
  • Single-threaded JS
  • Call stack in JS
  • Hoisting

Scope

Definition :

  • The Scope is the current context of execution in which variables are accessible or can be referenced.
  • If a variable is not in the current scope, then it will not be available for use inside that scope.
  • Child scopes have access to parent scope but not vice versa.

3 Types of scopes available in Javascript :


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

Global Scope :

Variables which are declared outside any function have global scope. Global variables can be accessed anywhere in a Javascript program.

example:
var x=2;
let y = 3;
const z = 4;

Here Variable x, y and z have Global scope and they can be accessible anywhere in Javascript program.

Block Scope :

Variables declared within { } block can be accessed only in that block and not outside of the block. But variables declared with var keyword does not have block scope, they can be accessible outside the block as well.

example 1:
    {
        let x = 2;
        // x can be used here
    }

    // x can not be used here
example 2:
    {
        var y = 3;
        // y can be used here
    }
    // y can be used here as well, Since it is declare with var.

Function Scope :

Javascript has a function scope, Each function creates a new Scope. Variables defined inside a function are not accessible outside the function or in another function.

example :
    function demo() {
        let x = 10;
        // x can be used here
    }
    // x cannot be used here

Single Threaded Javascript

  • Javascript is a single threaded language, it means it has only one call stack that is used to execute the program.
  • The call stack is same as the stack data structure. And as we know stacks are Last In First Out.
  • Similarly, within the call stack, whenever a line of code gets inside, it executes and move out of the call stack.
  • In this way, Javascript is a single- threaded language because of only one call stack.
  • Since, Javascript is a single threaded language, it is synchronous in nature. Now you will wonder why do we have async calls in Javascript if JS is synchronous language.
  • Let me explain you the concept of async calls in JS and how it is done in single-threaded JS language.
  • Before jumping to understand asynchronous calls in JS ,let’s first understand why async calls are required in the first place.
  • So, as we know within the synchronous calls, execution is done line by line which means one task is executed and then the second task executes. Due to this synchronisation, there arises the problem of time wastage and resource wastage.
  • These problems are overcome by Async calls. In asynchronous calls, One task doesn’t wait for the other task for it’s completion. It start its execution simultaneously. Therefore whenever we don’t want our task to wait for other task to get completed, we use async calls.
  • Now, how async calls are executed in single threaded JS? Let me explain this to you.
  • Within JS we have Lexical Environment, Syntax parser and Execution Context (Memory Heap and Call Stack) which are used to execute JS code. But along with these browsers also have Event loop, Callback Queue And Web APIs that is also used to execute the JS code.

Javascript Runtime Environment.png

  • As you can see in above image, DOM, Timeout and AJAX are not part of JS but the part of browser. So they can run asynchronously within WEB APIs using callback queue and put into call stack using event loop.

  • I know I know, this might sound a little confusing but let me help you to understand this with the help of one example.

  • Suppose we are executing below code in the JS runtime environment.
  console.log(‘Hello’);

  setTimeout( () => {
    console.log(‘’Hi);
  }, 4000);

  console.log(‘Hey’);

Output : Hello Hey Hi

  • So, let’s try to understand why this output is coming like this even if JS is synchronous in nature.
  • When JS tries to execute above program, It goes to statement 1, add it to the call stack, execute it and remove it from call stack. Now it goes to statement 2, add it to the call stack but when try to execute it finds out that setTimeout() function is not part of JS but part of browser, so it remove it from call stack and put it into Web API to execute. And now call stack is empty, statement 3 is put into call stack for execution. Therefore statement 3 is executed before statement 2.
  • Meanwhile Web API put seTimeu in the call-back queue for execution. Event loop checks whether call stack is empty or not. As son as Event loop finds out that call stack is empty, it put statement 3 in the call stack for execution hence statement 3 is executed.

Call Stack in Javascript

The call stack is a mechanism for an interpreter to keep track of function calls. It is use to understand what function is currently being run and what functions are called from within that function.

  • When program executes a function, Interpreter add that function to call stack and start its execution. If that function calls some other function, then that new function is also added to the call stack for execution After its execution, it is removed from the call stack and resumes execution where it was called.

Example

function func1() {
    func2();
    console.log(‘Hello from func1’);
}

Function func2() {    
    console.log(‘Hello from func2’);
}


// func1 invoking
func1();

Output: Hello from func2 Hello from func1

Explanation of above code execution:

Step 1: When code reaches to the invocation of func1(), it adds func1 to the call stack for execution. Call Stack.png

Step 2: Execution of func1 starts and when it reaches to the invocation of func2() inside func1(), Execution context of func2() is added to the call stack.

Call Stack (1).png

Step 3: func2() execution is started and console.log of func2() gets executed which prints ‘Hello from func2’ to the console.

Step 4: When interpreter finds out that there is no more lines in func2() for execution, it removes func2() from call stack and execution context will go to the point where func2() was called. (From func1)

Call Stack (2).png

Step 5: Then console.log() of func1() gets executed and ’Hello from func1’ gets printed to the console. And since there is no code for execution after this, Execution context of func1 is removed from call stack.

Call Stack (3).png

Hoisting

Hoisting is a process in JS where Interpreter move declaration of variables, functions and classes to the top of their scope, before the execution of the code.

Function Hoisting

  • One of the advantages of hoisting is that it lets you use a function before you declare it in your code.
hello(‘Jack’);

function hello(name) {
  console.log(`hello from ${name}`);
}
/*
The result of the code above is: "hello from Jack”
*/
  • Without hoisting you would have to write the same code like this:
function hello(name) {
  console.log(`hello from ${name}`);
}

hello(‘Jack’);
/*
The result of the code above is: "hello from Jack”
*/

Variable Hoisting

Variable hoisting is you can use variables before they are declared/ initialised.

Var hoisting :

  • Here we declare and then initialize the value of a var after using it. The default initialization of the var is undefined.
  console.log(num); // Returns 'undefined' from hoisted var declaration (not 6)
  var num; // Declaration
  num = 6; // Initialization
  console.log(num); // Returns 6 after the line with initialization is executed.

The same thing happens if we declare and initialize the variable in the same line.

console.log(num); // Returns 'undefined' from hoisted var declaration (not 6)
var num = 6; // Initialization and declaration.
console.log(num); // Returns 6 after the line with initialization is executed.

let and const hoisting :

Variables declared with let and const are also hoisted but, unlike var, are not initialized with a default value. An exception will be thrown if a variable declared with let or const is read before it is initialized.

  console.log(num); // Throws ReferenceError exception as the variable value is uninitialized
  let num = 6; // Initialization

Class Hoisting

  • Classes defined using a class declaration are hoisted, which means that JavaScript has a reference to the class.
  • However the class is not initialized by default, so any code that uses it before the line in which it is initialized is executed will throw a ReferenceError.

Class declarations :

One way to define a class is using a class declaration. To declare a class, you use the class keyword with the name of the class ("Person" here).

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

Thank you for reading this article, do like and share if you liked this article. Suggestions and comments are appeciated.