Top 10 Most Asked JavaScript Interview Questions With Answers Part 06

Top 10 Most Asked JavaScript Interview Questions With Answers Part 06

Question No 1:

What is a promise

A promise is an object that may produce a single value sometime in the future with either a resolved value or a reason that it’s not resolved(for example, network error). It will be in one of the 3 possible states: fulfilled, rejected, or pending.

The syntax of Promise creation looks like below,

const promise = new Promise(function (resolve, reject) {      // promise description    });

The usage of a promise would be as below,

const promise = new Promise(      
(resolve) => {
setTimeout(() => {
resolve("I'm a Promise!");
}, 5000);
},
(reject) => {} );
promise.then((value) => console.log(value));

The action flow of a promise will be as below,

Question No 2:

Why do you need a promise

Promises are used to handle asynchronous operations. They provide an alternative approach for callbacks by reducing the callback hell and writing the cleaner code.

Question No 3:

What are the three states of promise

  1. Promises have three states:
  2. Pending: This is an initial state of the Promise before an operation begins
  3. Fulfilled: This state indicates that the specified operation was completed.
  4. Rejected: This state indicates that the operation did not complete. In this case, an error value will be thrown.

Question No 4:

What is a callback function?

A callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action. Let’s take a simple example of how to use a callback function

function callbackFunction(name) {      
console.log("Hello " + name);
}
function outerFunction(callback) {
let name = prompt("Please enter your name.");
callback(name);
}
outerFunction(callbackFunction);

Question No 5:

Why do we need callbacks

The callbacks are needed because javascript is an event-driven language. That means instead of waiting for a response javascript will keep executing while listening for other events. Let’s take an example with the first function invoking an API call(simulated by setTimeout) and the next function which logs the message.

function firstFunction() {      // Simulate a code delay      setTimeout(function () {        console.log("First function called");      }, 1000);    }    function secondFunction() {      console.log("Second function called");    }    firstFunction();    secondFunction();        Output;    // Second function called    // First function called

As observed from the output, javascript didn’t wait for the response of the first function and the remaining code block got executed. So callbacks are used in a way to make sure that certain code doesn’t execute until the other code finishes execution.

Question No 6:

What is callback hell?

Callback Hell is an anti-pattern with multiple nested callbacks which makes code hard to read and debug when dealing with asynchronous logic. The callback hell looks like below,

async1(function(){        
async2(function(){
async3(function(){
async4(function(){
....
});
});
});
});

Question No 7:

What are server-sent events?

Server-sent events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling. These are a one-way communications channel — events flow from server to client only. This has been used in Facebook/Twitter updates, stock price updates, news feeds etc.

Question No 8:

How do you receive server-sent event notifications

The EventSource object is used to receive server-sent event notifications. For example, you can receive messages from the server as below,

if (typeof EventSource !== "undefined") {      var source = new EventSource("sse_generator.js");      source.onmessage = function (event) {        document.getElementById("output").innerHTML += event.data + "";      };    }

Question No 9:

How do you check browser support for server-sent events

You can perform browser support for server-sent events before using it as below,

if (typeof EventSource !== "undefined") {      
// Server-sent events supported. Let's have some code here!
} else {
// No server-sent events supported
}

Question No 10:

What are the events available for server-sent events

Below is the list of events available for server-sent events

onopen

It is used when a connection to the server is opened

onmessage

This event is used when a message is received

onerror

It happens when an error occurs

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Muhammad Umair

Muhammad Umair

93 Followers

MERN Stack Developer | Software Engineer| Frontend & Backend Developer | Javascript, React JS, Express JS, Node JS, MongoDB, SQL, and Python