DEV Community

Deepak Govindarajan
Deepak Govindarajan

Posted on

Interview Questions in Javascript & Node.js

Image description

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:

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()
Enter fullscreen mode Exit fullscreen mode

Output:

I am current event loop
I am nextTick
I am setTimeout
I am setImmediate
Enter fullscreen mode Exit fullscreen mode

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:

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

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

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

initClosure(); 
Enter fullscreen mode Exit fullscreen mode

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

var initClosure = showBiodata();
Enter fullscreen mode Exit fullscreen mode

The returned function is then executed when we invoke initClosure:

initClosure();
Enter fullscreen mode Exit fullscreen mode

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,

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


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

  let message;
}
showWelcome();
Enter fullscreen mode Exit fullscreen mode

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,

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
Enter fullscreen mode Exit fullscreen mode

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,

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]
Enter fullscreen mode Exit fullscreen mode

5. What is the difference between Promise and Observable?

Image description


6. What is the output of the below program?

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

runner()
Enter fullscreen mode Exit fullscreen mode

Output:

3
3
3
Enter fullscreen mode Exit fullscreen mode

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:

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)
Enter fullscreen mode Exit fullscreen mode

Output:

false 
false
false
true
Enter fullscreen mode Exit fullscreen mode

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:

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

console.log(runner().name)
Enter fullscreen mode Exit fullscreen mode

Output:

Uncaught TypeError: Cannot read properties of undefined
Enter fullscreen mode Exit fullscreen mode

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

function runner(){
    return {
        name: "Rayn Dahl"
    }
}
console.log(runner().name)
Enter fullscreen mode Exit fullscreen mode

Output:

Rayn Dahl
Enter fullscreen mode Exit fullscreen mode

8. What is the output of the below program?

let name = "Rayn";

(function showName() {
    if (name === "Rayn") {
        let name = "Rayn Dahl";
        console.log(name);
    }
    console.log(name);
})();
Enter fullscreen mode Exit fullscreen mode

Output:

Rayn Dahl
Rayn
Enter fullscreen mode Exit fullscreen mode

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?

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

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

Enter fullscreen mode Exit fullscreen mode

output:

2
5
1
2
1
Enter fullscreen mode Exit fullscreen mode

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

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");
Enter fullscreen mode Exit fullscreen mode

Output:

Hello world
Hello JavaScript
Enter fullscreen mode Exit fullscreen mode

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

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)
Enter fullscreen mode Exit fullscreen mode

Output:

Rayn Dahl
45
IT
developer
Enter fullscreen mode Exit fullscreen mode

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


Top comments (0)