Javascript Interview Preparation Cheat sheet

Javascript Interview Preparation Cheat sheet

Today we will cover 4 topics which are most important and mosked asked in the Javascript interview.

  1. Scope
  2. Single threaded javascript
  3. call stack in javascript
  4. hoisting in javascript

Scope

Scope defines the lifetime or accessibility of the variable. variables are not accessible outside the scope where they are declared.

image.png

Type of Scope in Javascript

1. functional scope

In JavaScript, each function creates a new scope. Variables defined inside a function are not accessible or visible from outside the function. In functional scope the functionality of the let, var and const are same.

function do() {
  let car = "Volvo";      // Function Scope
}
console.log(carName);        //car not defined

2. Block Scope

Variables declared inside the blocks like braces { } or loops with the type of let or const are block scoped. var doesn't have block scope. They can't be accessible outside that blocks.

let x = 1;
{ 
  let y = 2;
}
console.log(x);    // 1
console.log(y);    // y is not defined

here y is inside the block and let has block scope. so It cant be accessible outside that block.

3. Global Scope

The global scope is the most outer scope in javascript. Variable declared with global scope can be accessible from anywhere.

\\script.js
let message = "this is global scope";
// here accessible
function(){
// here accessible
}

4. Local Scope

Those variable that can be accessed for a specific region of the code are called local scope. let and const variable inside the function has local scope. They can't be visible outside of the function.

var num;
function print(){
  const arr = [1,2,3,4,5];
}
console.log(arr);      //arr is not defined

here, array is declared inside the function so it can't be able to access outside the function. so it is local for that function only.

Conclusion

Variables defined in global scope are available everywhere in the application.

Variables declared with let and const have block scope. var doesn’t have block scope.

Function scope means that parameters and variables defined in a function are only accessible within that function


Javascript is single threaded synchronous programming language. Why it is ?

Thread is the execution of running multiple tasks or programs at the same time. Each unit capable of executing code is called a thread.

JavaScript is a single-threaded language because while It running code on a single thread, it can be really easy to implement as we don’t have to deal with the complicated scenarios like deadlock which is quite a bit familiar in languages like java.

Since, JavaScript is a single-threaded language, it is synchronous in nature. But we can also make it asynchronous using some techniques.

sometimes synchronous can be harmful when a function takes awhile to execute or has to wait on something, it freezes everything up in the meanwhile. eg. In some scenarios, user get alert box and this case they can't interect with the webpage until they hit OK or cancel buton.

then how do we get asynchronous code with Javascript?

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

Let's understand it by taking an example

console.log("first log")
setTimeout(() => {
    console.log("second log")
}, 5000)
console.log("third log")

// first
// third
// second

here we defined the set timeout method after the first console.log. so what js engine do is that first line of code is executed. after that setTimeout method comes, which isn't handled by Javascript, and pushes it off to the WebAPI to be done asynchronously. Then it further executes the program. So the "third log" will be printed next and after the setTimeout is complete then finally it prints the "second log".


Call stack

At the most basic level, a call stack is a data structure to temporarily store and manage function invocation (call). This stack follow the LIFO order (last in first out)

Javascript is interpreted language. which means js engine compiles Javascript line by line. 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 first(){
  console.log("Hello");
}
function second(){
first();
  console.log("World");
}
second();

output:

Hello
World

Let's see what happens when we execute this program.

  1. First call stack is empty. js engine scans the whole program and the global execution context created.

  2. when the second() gets executed, an interpreter gets call of the first() method. so it pushes it into the call stack.

  3. then first() will be pushed into the stack.

  4. now first() print the "Hello" to the console. and first() is pop from the stack.

  5. then second() will print "World" and to the console and second() method pop out from the stack.

  6. as soon as the second() pop out from the stack, and it clears the memory.

image.png


Hoisting

Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution. It gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.

The basic sequence is function declaration and definition and then call(use that function).

But Hoisting allows functions to be safely used in code before they are declared. The advantage is that it allows us to use a function before declaring it.

In Javascript variable, class and function can be hoisted.

1. Variable Hoisting

In javascript the variables declared with var is hoisted and let, const does not allow hoisting.

num = 14;
console.log(num);        //14
var num

here we are initializing and printing the number before the declaration. It works. let's see what happens when we print variable before initialization.

console.log(num);     // Returns 'undefined'
var num = 6;

In this case, it returns undefined because initialization is not hoisted in javascript.

2. Function hoisting

A function can be called before the declaration. we can see it by the below example.

carName("Maruti");

function carName(name) {
  console.log(`I have a  ${name} car.`);
}

output:

I have a  Maruti car

In this case, the function carName is called before declaring it and program shows the output because of hoisting.

in other cases when the function is used as an expression, an error occurs because only declarations are hoisted.

carName("Maruti");

var carName = function(name) {
  console.log(`I have a  ${name} car.`);
}

Output :

carName("Maruti");
^

TypeError: carName is not a function