JavaScript Interview cheat sheet

JavaScript Interview cheat sheet

scope

The scope is the current context of execution in which variables and functions are visible and can be referenced. scope is layered in hierarchy that all child scopes will have access to the variables or functions that are declared in the parent scope, parent scopes will not be having access to the child scope.

image.png

Types of scopes available in JavaScript

  • Global scope
  • Local Scope
    • Block Scope
    • Function Scope

image.png

Global Scope:

In programming environment global scope is scope which contains all scopes and is visible to all other scopes.

In JavaScript Global Scope is generally a webpage in all code is contained and executed

var name = "aditya";
function returnName() {
    console.log(name);
};

In this example variable name is accessible in the function returnName because variable name in global scope.

Local scope:

When you create variables in JavaScript function with var let const keywords these variable are local to the function or block and only accessible with in the function or block. This is called local scope.

There are two types of local scopes they are

  • Block Scope we can safely say that a block is the content between the brackets{ } we can observe this in if else statements and for loops and these block scoped variables are declared using let const In this example iis in for loop so we can't access that out side of the loop. we will get an error

     for (let i = 0; i < 2; i++) {  
         // ...  
         }
    
     console.log(i) 
     // The i variable isn't defined.
    
  • Function Scope When we create a variable inside a function it is accessible inside the function this is called function scope In this example total is a variable that is only accessible inside the function sum
      function sum(a, b) {
          var total = a + b;
          return total;
      };
      sum(3, 5);
    

Single Threaded

JavaScript is a single threaded synchronous language

What is a thread?

A thread in computer science is the execution of running multiple tasks or programs at the same time. Each unit capable of executing code is called thread

The main thread is the one used by the browser to handle user events, render and paint the display, and to run the majority of the code that comprises a typical web page or app. Because these things are all happening in one thread, a slow website or app script slows down the entire browser; worse, if a site or app script enters an infinite loop, the entire browser will hang. This results in a frustrating, sluggish (or worse) user experience.

However, modern JavaScript offers ways to create additional threads, each executing independently while possibly communicating between one another. This is done using technologies such as web workers, which can be used to spin off a sub-program which runs concurrently with the main thread in a thread of its own. This allows slow, complex, or long-running tasks to be executed independently of the main thread, preserving the overall performance of the site or app as well as that of the browser overall. This also allows individuals to take advantage of modern multi-core processors.

A special type of worker, called a service worker, can be created which can be left behind by a site—with the user's permission—to run even when the user isn't currently using that site. This is used to create sites capable of notifying the user when things happen while they're not actively engaged with a site. Such as notifying a user they have received new email even though they're not currently logged into their mail service.

Overall it can be observed these threads within our operating system are extremely helpful. They help minimise the context switching time, enables more efficient communication and allows further use of the multiprocessor architecture.

image.png [[single and multi threaded]]

Call stack

Overall it can be observed these threads within our operating system are extremely helpful. They help minimize the context switching time, enables more efficient communication and allows further use of the multiprocessor architecture.

  • When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function.
  • Any functions that are called by that function are added to the call stack further up, and run where their calls are reached.
  • When the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing.
  • If the stack takes up more space than it had assigned to it, it results in a "stack overflow" error.
function greeting() {
  // [1] Some code here
  sayHi();
  // [2] Some code here
}
function sayHi() {
  return "Hi!";
}

// Invoke the `greeting` function
greeting();

// [3] Some code here

The code above would be executed like this:

  1. Ignore all functions, until it reaches the greeting() function invocation.
  2. Add the greeting() function to the call stack list.
  3. Execute all lines of code inside the greeting() function.
  4. Get to the sayHi() function invocation.
  5. Add the sayHi() function to the call stack list.
  6. Execute all lines of code inside the sayHi() function, until reaches its end.
  7. Return execution to the line that invoked sayHi() and continue executing the rest of the greeting() function.
  8. Delete the sayHi() function from our call stack list.
  9. When everything inside the greeting() function has been executed, return to its invoking line to continue executing the rest of the JS code.
  10. Delete the greeting() function from the call stack list.

In summary, then, we start with an empty Call Stack. Whenever we invoke a function, it is automatically added to the Call Stack. Once the function has executed all of its code, it is automatically removed from the Call Stack. Ultimately, the Stack is empty again.

image.png [[call stack]]

Hoisting

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.

Hoisting allows functions to be safely used in code before they are declared.

Variable and class declarations are also hoisted, so they too can be referenced before they are declared. Note that doing so can lead to unexpected errors, and is not generally recommended.

Function hoisting:

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

catName("Tiger");

function catName(name) {
  console.log(`My cat's name is ${name}`);
}
/*
The result of the code above is: "My cat's name is Tiger"
*/

Without hoisting you would have to write the same code like this:

function catName(name) {
  console.log(`My cat's name is ${name}`);
}

catName("Tiger");
/*
The result of the code above is the same: "My cat's name is Tiger"
*/

Variable hoisting

Hoisting works with variables too, so you can use a variable in code before it is declared and/or initialized.

However, JavaScript only hoists declarations, not initializations! This means that initialization doesn't happen until the associated line of code is executed, even if the variable was originally initialized then declared, or declared and initialized in the same line.

Until that point in the execution is reached the variable has its default initialization (undefined for a variable declared using var, otherwise uninitialized).

Below are some examples showing what can happen if you use a variable before it is declared.

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.

If we forget the declaration altogether (and only initialize the value) the variable isn't hoisted. Trying to read the variable before it is initialized results in a ReferenceError exception.

console.log(num); // Throws ReferenceError exception - the interpreter doesn't know about `num`.
num = 6; // Initialization

Thanks for reading the article for more in depth understanding refer to MDN Docs