JS Interview Cheatsheet

Manik walks us through his JavaScript Cheatsheet and shares his top tips for growing as a JS developer through this short, snazzy, precise and content

Β·

13 min read

JS Interview Cheatsheet

In this article we look at some important JS concepts and topics which would actually help you grasp a hold on your JS interview prep. I hope you all benefit as much from reading and implementing these as I benefited from researching and writing this πŸ‘ΎπŸ‘ΎπŸ‘Ύ


πŸ§‘β€πŸš€ SCOPE

scope.png


🎭 What is Scope ?

  • The scope is the current context of execution in which values and expressions are "visible" or can be referenced. If a variable or expression is not in the current scope, it will not be available for use. Scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa.
  • In other words, scope refers to the boundary in which a variable or expression is relevant or holds certain meaning.

For example, consider the below code :

let nam = 'Manik';
const sal = 50000;

function display(){
    console.log(`Name is ${nam}`);
    console.log(`Salary is ${sal}`);

    let sample = 90;
    console.log(sample);
}

display();
console.log(sample);

Now consider the error this code generates upon execution :

scope1.JPG

In this program, the area/boundary in which the variable 'sample' operates or is relevant lies within the function 'display'. Hence, since the scope of the variable is only limited to the function, accessing it out of scope gives an error message.


✨ Types of Scope

  • Global scope : The default scope for all code running in script mode.
  • Module scope : The scope for code running in module mode.
  • Function scope : The scope created with a function.
  • Block scope : The scope created with a pair of curly braces (a block).

Now let us understand these one by one through examples as scope as a concept is best understood by actual programs that work.

πŸ›Ί Global scope

let global_IP = '192.168.11.34';
console.log(global_IP);
  • In the above code, the variable 'global_IP' is defined outside any function, block, or module scope and hence, has global scope.
  • This means, it can be accessed from anywhere in the program.

πŸš• Module scope

// In country.js, exporting to local.js

export { countries, states, print };
  • In the above code, suppose we need a function or object available which is present in a different module or js file available to other modules, we use the keyword 'export'.
  • Importing makes a function or object, from other modules, available to the current module.

πŸ›΅ Function scope

function sayHi(){
    let word = 'Hi there!';
    console.log(word);
}

sayHi();
console.log(word);

scope2.JPG

  • In the above code, the variable 'word' is only available within the function 'sayHi()' so trying to access it outside the function would throw an error.
  • You may use the variable 'word' by calling the function 'sayHi()'.

πŸš΄β€β™‚οΈ Block scope

let x = 10;

{
    let x = 20;
    console.log(x);
}

console.log(x);

scope3.JPG

  • In the above code, the variable x defined within the curly braces {} has a boundary only within that curly braces, hence printing to console gives varied results when used within and outside the scope.

πŸ±β€πŸ‰ Lexical Scope

  • Lexical scope is the ability of the inner function to access the outer scope in which it is defined.
  • You may call it as a hierarchical access given to inner scope from outer scope.
let outer = 10;

function sum() {
    let inner = 20;
    function innerSum(n) {
        let innerMore = 30;
        return outer+inner+innerMore+n;
    }
    return innerSum;
}

let summer = sum();
console.log(summer(100));

scope4.JPG

  • In the above code, variable 'outer' is present in global scope hence, can be accessed by 'sum()' and 'innerSum()' both as all 3 scopes are linked hierarchically.
  • The variable 'inner' has a function-level scope within 'sum()' hence, can be accessed by 'innerSum()'.
  • The variable 'innerMore' is within 'innerSum()' hence, can only be accessed within this function and not anywhere outside.

⛓️ Scope Chaining

  • It is the process in which, JavaScript engine searches for the value of the variables in the scope of the functions. However, the search is in a lexical manner. First of all the engine looks out in the current scope of the current function. If not found, it finds it in the parent function.
let x = 100;
let y = 200;

function print(){
    console.log(y); //Error : Trying to access before initialization ; Note that y is also present in global scope
    let y = 300;
    console.log(y);
    function innerPrint(){
        console.log(x);
        let x = 300;
        console.log(x);
    }
    return innerPrint;
}

let myPrint = print();
myPrint();

scope5.JPG

  • The above code gives an error, but why should it ? 'x' and 'y' both are defined in global as well as function level scope.
  • Due to scope chaining, first the current scope is checked and here it finds 'y' initialized so it does not look for the globally scoped 'y'.
  • It wants the currently scoped 'y' to be used but as it is initialized afterwards it shows a Reference Error.

Similarly, if we comment the error line having 'y', it will show error on 'x':

let x = 100;
let y = 200;

function print(){
    // console.log(y);
    let y = 300;
    console.log(y);
    function innerPrint(){
        console.log(x);
        let x = 300;
        console.log(x);
    }
    return innerPrint;
}

let myPrint = print();
myPrint();

scope6.JPG

Due to this, if both conflicting 'x' and 'y' are commented out, the due to scope chaining, the global 'x' and 'y' are printed :

let x = 100;
let y = 200;

function print(){
    // console.log(y);
    // let y = 300;
    console.log(y);
    function innerPrint(){
        // console.log(x);
        // let x = 300;
        console.log(x);
    }
    return innerPrint;
}

let myPrint = print();
myPrint();

scope7.JPG


πŸ§‘β€βš–οΈ SINGLE THREADING

threading.png


πŸ΄β€β˜ οΈ What is a thread ?

  • A thread in computer science is the execution of running multiple tasks or programs at the same time.
  • You can say that a thread is like a process which executes multiple operations line by line in a sequential fashion.

threadii.JPG

  • The main thread is where a browser processes user events and paints. By default, the browser uses a single thread to run all the JavaScript in your page, as well as to perform layout, reflows, and garbage collection. This means that long-running JavaScript functions can block the thread, leading to an unresponsive page and a bad user experience.

☠️ How is JS single-threaded ?

  • Javascript engine runs on a V8 engine that has a memory heap and a call stack.
  • JS is a single threaded which means only one statement is executed at a time.
  • In other words, we can say JS is by default synchronous in nature.
  • Synchronous (or sync) execution usually refers to code executing in sequence. In sync 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.

Let us take the below example :

console.log('Hi There!');

console.log('My Name is');

console.log('Manik!');

th1.JPG

In the above code, each statement executes line by line making it synchronous.


🦜 So deep down how does single-threading work in JS ?

  • Javascript is a single threaded language that can be non-blocking.
  • Single threaded means it has only one call stack. Whatever is on the top of the call stack is run first.

Let us take the below example :

function call(){
    console.log('Hi There!');
    function me(){
        console.log('My Name is');
        function soon(){
            console.log('Manik!');
        }
        soon();
    }
    me();
};

call();

th2.JPG

Now please look closely how this works within the call stack as is pretty evident on the browser console's debugger window :

th3.JPG

th4.JPG

th5.JPG

So in the above code as you may see, the function calling works like a stack : LIFO way - Last In, First Out. This means at the beginning of the code, 'call()' gets pushed in the stack, then 'me()' is pushed and finally 'soon()' is pushed.


βš“ Blocked Call Stack in JS

  • The synchronous behavior of JS may cause a problem as it may unnecessarily block further execution of the program.

Let us take below example :

console.log('A');

for(i=0; i<= 100000000000000000000000; i++){};
console.log('B');

console.log('C');

In the above code, if a portion of code needs heavy execution, this may cause the whole program execution to get blocked. This would create a problem considering the single-threaded nature of JS.


🀠 Asynchronous Behavior

  • JS can also be non-blocking and behave as if it were multi-threaded.
  • It means that it doesn't wait for the response of an API call, I/O events, etc., and can continue the code execution.
  • Asynchronous (or async) execution refers to execution that doesn’t run in the sequence it appears in the code. In async programming the program doesn’t wait for the task to complete and can move on to the next task.
  • Different languages have different ways to implement asynchronous. The most popular is through Multi-threading.
  • In brief, Java implements multi-threading by creating a child thread which does it’s own separate execution and then merges back with the parent thread.
  • This however can run into a problem known as Deadlock, which can be dealt with various deadlock prevention mechanism.

Let us see from below example, how asynchronous in JavaScript is implemented :

console.log('A');

setTimeout(() => {
    console.log('B');    
}, 3000);

console.log('C');

th6.JPG

In the above code, 'B' gets printed after 'C' as 'B' which may denote a very heavy process gets shifted to a timeout instruction.

  • In a nutshell, 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 like setTimeout() that requires extra time to execute then call stack will pop that out and send it to Web API.

  • 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.

th7.JPG

  • In Javascript, All instructions are put on a call stack. When the stack arrives at setTimeout, the engine sees it as a Web API instruction and pops it out and sends it to Web API. Once the Web API is done with the execution, it will arrive at the call back queue.
  • The engine checks if the call stack is empty. If it is empty, then we check callback queue which has the instruction setTimeout in it. The callback queue sends it to call back stack and the instruction is executed.

πŸ›€ CALL STACK

stack2.JPG


πŸ”± What is the Call Stack in JS ?

  • Call stack is used by JavaScript to keep track of multiple function calls.
  • It is basically like the popular data structure 'stack' where data can be pushed and popped and follows the Last In First Out (LIFO) principle.
  • 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.

🈹 How Call Stack works in JS ?

Let us look at the below example to see how the call stack works :

function greet1() {
  console.log("Namaste");
}

function greet2() {
  greet1();
  console.log("Chai Pee Lo!");
}

greet2();

Step 1 :

When the code loads in memory, the global execution context gets pushed in the stack.

call1.JPG

Step 2 :

The greet2() function gets called, and the execution context of greet2() gets pushed into the stack.

call2.JPG

Step 3 :

The execution of greet2() starts and during its execution, the greet1() function gets called inside the greet2() function. This causes the execution context of greet1() to get pushed in the call stack.

call3.JPG

Step 4:

Now the greet1() function starts executing. A new stack frame of the console.log() method will be pushed to the stack.

call4.JPG

Step 5:

When the console.log() method runs, it will print β€œNamaste” and then it will be popped from the stack. The execution context go will back to the function and now there not any line of code that remains in the greet1() function, as a result, it will also be popped from the call stack.

Step 6:

This will similarly happen with the console.log() method that prints the line β€œChai Pee Lo!” and then finally the function greet2() would finish and would be pushed off the stack.


πŸ»β€β„οΈ HOISTING

Hoisting.png


πŸ₯­ What is Hoisting ?

  • It 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.

🍈 Function hoisting

  • It refers to using a function before it is declared.

Example :

greetMe();

function greetMe(){
    console.log("Hello There!");
}

h1.JPG


🍍 Variable hoisting

  • It refers to using a variable before it is declared.
  • But JS only hoists declarations, not initializations.
  • 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.

πŸ“ Initialization Defaults :

  • 🌢️ var hoisting

    • Default value : 'undefined'.
  • Using before declaration / initialization
console.log(num); //Prints undefined as initialization happens afterwards

var num = 100;

h2.JPG

  • Using before declaration / initialization and not specifying 'var' keyword explicitly
console.log(num); // Throws ReferenceError exception - the interpreter doesn't know about `num`.

num = 100;

h3.JPG

  • Using after declaration / initialization and not specifying 'var' keyword explicitly
num = 100;

console.log(num);

h4.JPG

  • 🌽 let and const hoisting

    • Default value : 'undefined', provided declaration comes before use.
let num;

console.log(num);

h5.JPG

  • An exception will be thrown if a variable declared with let or const is read before it is initialized or declared.
console.log(num); 

let num = 100;

h6.JPG

  • Please note that it is the order in which code is executed that matters, not the order in which it is written in the source file. The code will succeed provided the line that initializes the variable is executed before any line that reads it.
function display(){
    console.log(num); //Within function
}

let num=100;

display();

h7.JPG

console.log(num); //Without function

let num=100;

display();

h8.JPG


🍌 Temporal Dead Zone (TDZ)

  • A let or const variable is said to be in a "temporal dead zone" (TDZ) from the start of the block until code execution reaches the line where the variable is declared and initialized.
  • While inside the TDZ, the variable has not been initialized with a value, and any attempt to access it will result in a ReferenceError. The variable is initialized with a value when execution reaches the line of code where it was declared. If no initial value was specified with the variable declaration, it will be initialized with a value of undefined.

  • πŸ₯¬ BUT THERE IS A CATCH !!!

    • The code behaves a little differently in the TDZ when seen in the debugger mode of the browser.

Please check the below code :

console.log(num); //Without function

let num=100;

display();

h9.JPG

  • Here num is given the default value of 'undefined' in the TDZ in the 'Script scope'.

But as soon as the TDZ is exited, this will show a ReferrenceError :

h10.JPG


🐾🐾🐾Conclusion 🐾🐾🐾

With all the above mentioned concepts in check, you would probably be set for trying out your first JS interview sessions or may want to try out with some mock sessions before you come out all guns blazing in the arena of JS 🦝🦝🦝

πŸŽ‚πŸŽ‚πŸŽ‚ Keep Hustling πŸŽ‚πŸŽ‚πŸŽ‚

Β