Javascript Interview Preparation Cheatsheet

Javascript Interview Preparation Cheatsheet

Scope

what is the scope in javascript?

Scope refers to the availability of variables and functions in certain parts of the code.

In JavaScript, a variable has two types of scope:

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

However, there used to be only two types of scopes before ES6, the global scope, and the local scope. But, with ES6 local scope was broken down into function scope and block scope.

GlobalScop.png

Let’s start with the global scope first.

1. Global Scope

The variable defined outside of any functions or curly brackets is called global variables and has a global scope. The variables are global scoped, which means they can be accessed from any part of the program, from any function, or even from a conditional state.

For Example:

<script>

    var globalScope = "car";

    function changeGlobalScope() {
            globalScope = "bike";
        };

    function showChangeGlobalScope() {
            alert(globalScope);
        };

    alert(globalScope); // car

    changeGlobalScope();
    showChangeGlobalScope();// bike

</script>

Note: As global variables are accessible through every code block, it is not a good practice to use them when they are not needed.

Local Scope

Within the global scope, whenever a new scope is created, for example, every time you create a function a new local scope gets created. Any variables created inside this local scope will be accessible only from within this function. Function parameters also get classed as being within the local scope.

There are two parts of local scope in ES6, function scope, and block scope. Let or const are the most commonly used variable these days. Each of these variables uses different scoping as shown below:

  • var: Function Scope
  • const: Block Scope
  • let: Block Scope

2. Function Scope

The function scope is the accessibility of the variables defined inside a function, these variables cannot be accessed from any other function or even outside the function in the main file.

For Example : First, we created a variable inside a function and accessed it inside the function:

function userName() {
  var text = "function scope";
  console.log(`This is a ${text}`);
}
userName();  // Output : This is a function scope

Note: If we try to access this variable outside of the function then we get an error:

For Example:

function userName() {
  var text = "function scope";
}
console.log(`This is a ${text}`);

userName();  // Output : ReferenceError: text is not defined.

3. Block Scope

Block scope is also a sub-type of local scope. Block scope means that every time a block is created so is a new local scope. When we create a variable within a block, that variable is then scoped to that block. This means that the variables are then not accessible from outside of the block. The block scope can be defined as the scope of the variables inside the curly brackets {}. Now, these curly brackets can be of loops, conditional statements, or something else. If you try to access a variable that is defined inside the block from outside of the block JavaScript will throw an error (a reference error).

For Example: We can create the function in that function and create variables inside curly brackets.

function add() {

  {
    let a = 4;
    const b = 8;
  }
  console.log(a + b);
}

add() // Output: ReferenceError: a is not defined

Note: The keywords let and const are used to define block variables.

For Example: We can create a condition that checks the marks obtained and shows whether they passed or failed.

let marksObtained = 45;

if(marksObtained >= 45){
 let status = "Passed";
 console.log("Subject Remarks: " + status);
}
else{
 let status = "Failed";
 console.log("Subject Remarks: " + status);
}  // Output: Subject Remarks: Passed

Note: If we refer to the local variable outside the function then we will get an error: "variable name is not defined". but we are going to remove the let keyword from the above code snippet and run the code then we get the output.

Single Thread

Javascript is a single-threaded language which means only one statement is executed at a time. it can be really easy to implement as we don't have to deal with the complicated scenarios that arise in the multi-threaded environment like a deadlock. It has only one stack. whenever the code runs, the global execution context is pushed inside the call stack and the code is executed one at a time.

For Example:

 alert("Hello World");

Note: we can't move forward or interact with the page unless we hit ok or close the alert box.

Call Stack

JavaScript Call Stack is a mechanism to keep track of the function calls. It is giving information on what function is currently being run and what functions are invoked from within that function.

JavaScript manages execution contexts through a call stack:

  • Global execution context
  • function execution contexts

The call stack works based on the LIFO principle i.e., last-in-first-out. When we execute a script, the JavaScript engine creates a global execution context and pushes it on top of the call stack.

global stack.png

Whenever a function is called, the JavaScript engine creates a function execution context for the function, pushes it on top of the call stack, and starts executing the function.

function1.png

If a function calls another function, the JavaScript engine creates a new function execution context for the function that is being called and pushes it on top of the call stack. When the current function completes, the JavaScript engine pops it off the call stack and resumes the execution where it left off.

function2.png

The script will stop when the call stack is empty.

Hoisting

In the JavaScript engine executes the JavaScript code, it creates the global execution context. The global execution context has two phases:

  • Creation
  • Execution

During the creation phase, the JavaScript engine moves the variable & function declarations to the top of your code. This is known as hoisting in JavaScript.Hoisting allows functions to be safely used in code before they are declared.

1. var Hoisting

Variable hoisting means the JavaScript engine moves the variable declarations to the top of the script.

For Example:

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

2. let & const Hoisting

Variables declared with let and const are also hoisted but, unlike var, are not initialized with a default value. Variables declared with let and const are hoisted. However, they are not initialized with undefined, or any value. Therefore, if they are used before they are initialized, we will get a ReferenceError.

For Example:

console.log(counter); // Output: ReferenceError: Cannot access 'counter' before initialization
let counter; // Declaration
counter = 1; // Initialization
console.log(counter); // Output : 1

3. Function Hoisting

It is also the JavaScript engine that hoists the function declarations. This means that the JavaScript engine also moves the function declarations to the top of the script.

For example:

let x = 5;
let y = 10;

let addition = add(x, y); 
console.log(addition); // Output:  15

function add(a, b) {
  return a + b;
}

4. Function Expressions

Changes the add from a regular function to a function expression:

For Example:

let x = 5;
let y = 10;

let addition = add(x, y); 
console.log(addition); // Output: ReferenceError: Cannot access 'add' before initialization

let add = function (a, b) {
  return a + b;
}

Note: Similar to the functions expressions, arrow functions are not hoisted.

Did you find this article valuable?

Support Saurabh Mehare by becoming a sponsor. Any amount is appreciated!