Interview Questions in Javascript & Node.js 

Tags: javascript, node, interview
Published: 2021-10-24 06:11:46

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0vl11bssk9fbfmo1z6jn.png)

## Javascript

JavaScript is a  scripting or programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities.

## Node.js

Node.js is a platform built on Google Chrome's JavaScript Engine (V8 Engine) for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

***

## 1. What is the difference between SetTimeout, setImmediate and process.nextTick?

Outwardly SetTimeout, setImmediate and process.nextTick are the functions that do the same thing. They execute the callback after the current event loop, but before anything else. 

### setTimeout:  
sets a timer which executes a function or specified piece of code once the timer expires.

### setImmediate:
It is used to break up long running operations and run a callback function immediately after the browser has completed other operations such as events and display updates.

### process.nextTick:
A function passed to process.nextTick() is going to be executed on the current iteration of the event loop, after the current operation ends. This means it will always execute before setTimeout and setImmediate.

### Example:

```javascript
function run() {
  setTimeout(() => console.log(" I am setTimeout"), 0);
  setImmediate(() => console.log("I am setImmediate"));
  process.nextTick(() => console.log("I am nextTick"));
  console.log("I am current event loop");
}

run()
```

### Output:
```
I am current event loop
I am nextTick
I am setTimeout
I am setImmediate
```

In this, callbacks are not executed in the same order.

In the above output the first one is "I am current event loop" and second one executed was process.nextTick, which puts its callback at the front of the event queue. It will execute after the code currently being executed but before I/O events or timers.

Next is "timeout". Since we passed setTimeout a timeout of 0, there is no additional enforced delay before its execution, and it is placed on into the timer queue during the next loop.

In the end, we have setImmediate which will be slower than setTimeout 0.

Generally event loop looks like this,

timers -> IO -> poll -> check ->close -> timers -> ...

**Timers:** callbacks from setInterval or setTimeout
**IO callbacks:** callbacks from I/O events
**Poll:** retrieve new I/O events
**Check:** callbacks from setImmediate execute here
**Close:** handle closed connections like sockets

***
## 2. Explain closures function?

Closures ability is to remember the variables and functions that are declared in its outer scope.

#### For Example:
```javascript
function showBiodata(){
  var employee = {
    name:"Rayn Dahl", 
    age:45,
    role: "Senior Programmer"
  };

  return function(){
    console.table(employee);
  }
}

var initClosure = showBiodata(); // Returns a function

initClosure(); 
```


The function showBiodata() gets executed and returns a function which we assigned to the variable:

```javascript
var initClosure = showBiodata();
```

The returned function is then executed when we invoke initClosure:

```javascript
initClosure();
``` 

#### Output:

| (index)       | Values              |
| ------------- |:-------------------:|
| name          | 'Rayn Dahl'         |
| age           | 45                  |
| role          | 'Senior Programmer' |

In showBiodata(), instead of destroying the value of employee after execution, saves the value in the memory for further reference. This is the reason why the returning function is able to use the variable declared in the outer scope even after the function is already executed.

This ability of a function to store a variable for further reference even after it is executed, is called Closure.

***

## 3. What is a Temporal Dead Zone?

Temporal Dead Zone occurs when we try to access a variable before it is initialized, while using let and const keyword

#### For Example,

```javascript
name = "Rayn Dahl"; // Gives reference error
let name;


function showWelcome(){
  message = "Welcome!!!"; // Throws a reference error

  let message;
}
showWelcome();
```
In the code above, we are trying to access variables which have not been declared yet

***

## 4. What is the difference between Rest parameter and Spread operator?

### Rest parameter:
Rest parameter allows a function to accept an indefinite number of arguments as an array,

#### For example,

```javsacript
function sum(...args){
  let total = 0
  args.forEach(item=>total+=item)
  return total
}

console.log(total(1,2)); //3
console.log(total(1,2,3)); //6
console.log(total(1,2,3,4)); //10
```

### Spread operator

Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. Also we can use this to merge two arrays

#### For example, 

```javascript
function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];
console.log(sum(...numbers)); // output: 6


let numberStore = [1, 2];
let newNumber = [3, 4];
numberStore = [...numberStore, ...newNumber];
console.log(numberStore) // output: [1,2,3,4]
```

***

## 5. What is the difference between Promise and Observable?

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hlh0yqkl0bq1lz3b57v0.png)

***

## 6. What is the output of the below program?

```javascript
function runner(){
  for(var i = 0; i < 3; i++){
    setTimeout(()=> console.log(i),1000);
  }
}

runner()
```

#### Output:
```
3
3
3
```
Variable declared inside the for loop with var keyword which does not have block scope. So the variable i is incremented first and then checked.

***
## 7. Guess the output of below code?

#### Code 1: 

```javascript
console.log(0.1 + 0.2 === 0.3)
console.log(0.1 + 0.7 === 0.8)
console.log(0.1 + 0.2 - 0.2 === 0.1)
console.log(0.1 + 0.4 === 0.5)
```

#### Output:
```
false 
false
false
true
```

0.1 +0.2 is equal to 0.30000000000000004
0.1 + 0.7 is equal to 0.7999999999999999
0.1 + 0.2 - 0.2 is equal to 0.10000000000000003

#### Code 2:

```javascript
function runner()
{
    return 
    {
        name: "Rayn Dahl"
    }
}

console.log(runner().name)
``` 

#### Output:
```
Uncaught TypeError: Cannot read properties of undefined
```

Program will never execute after return statement. To fix follow the below method

```javascript
function runner(){
    return {
        name: "Rayn Dahl"
    }
}
console.log(runner().name)
```

#### Output:

```
Rayn Dahl
```

***

## 8. What is the output of the below program?

```javascript
let name = "Rayn";

(function showName() {
    if (name === "Rayn") {
        let name = "Rayn Dahl";
        console.log(name);
    }
    console.log(name);
})();
```

#### Output:

```
Rayn Dahl
Rayn
```
Here showName is closure and it gets the name variable from the outer scope. The conditional has another local variable name which overwrites the outer name variable. So the first console.log displays value "Rayn Dahl". Where as the second console.log logs "Rayn" by capturing the name variable from outerscope.

*** 

## 9. What is the output of the below code?

```javascript
function sum(a = 1, b = 1) {
  return a + b
}

sum(); 
sum(2, 3);
sum('');
sum(null, 2);
sum(undefined, null)

```

#### output:

```
2
5
1
2
1
```
**sum()** - Here no arguments passed so default value 1 is taken and returned as 1+1=2
**sum(2,3)** - In this we have two arguments 2, 3 and returned as 2+3=5
**sum('')** - Here the first argument is string and second argument is not defined so default value 1 taken. "" + 1 = 1 (string concatenation)
**sum(null, 2)** - First argument is null and second argument is 2. null + 2 = 2 
**sum(undefined, null)** - Here the first argument is undefined so it take default value 1 and second argument is null. 1 + null = 1

***

## 10. What is the output of below programs?

#### Code 1

```javascript
let a = 0;
let b = new Number(0);

if(!a) console.log("Hello world");
if (!b) console.log("Hello Nodejs");
else console.log("Hello Javscript");
```
#### Output:

```
Hello world
Hello JavaScript
```
0 is false and !0 is true so "Hello world" is logged. 
new Number returns object, Objects is truthy so the above code block goes to else condition i.e., "Hello Javascript"

#### Code 2

```javascript
let { fullname: name, age, dept: department = "CSE", designation: role = "developer" } = { fullname: "Rayn Dahl", age: 45, dept: "IT" };

console.log(name);
console.log(age);
console.log(department);
console.log(role)
```

#### Output:
```
Rayn Dahl
45
IT
developer
```

The object property follows below rules,
The object properties can be retrieved and assigned to a variable with a different name
The property assigned a default value when the retrieved value is undefined

***