Skip to content

JavaScript 2

1. What are closures

A closure is the combination of a function bundled(enclosed) together with its lexical environment within which that function was declared.

JS
function Welcome(name) {
  var greetingInfo = function (message) {
    console.log(message + " " + name);
  };
  return greetingInfo;
}
const myFunction = Welcome("John");
myFunction("Welcome "); // Output: Welcome John
myFunction("Hello Mr."); // Output: Hello Mr. John

2. What is a service worker

A Service worker is basically a script (JavaScript file) that runs in the background, separate from a web page and provides features that don't need a web page or user interaction. Some of the major features of service workers are Rich offline experiences(offline first web application development), periodic background syncs, push notifications, intercept and handle network requests and programmatically managing a cache of responses.

Service worker can't access the DOM directly. But it can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM.

JS
// Check web workers browser support
if (typeof Worker !== "undefined") {
  // code for Web worker support.
} else {
  // Sorry! No Web Worker support..
}

3. What is IndexedDB & web storage

IndexedDB is a low-level API for client-side storage of larger amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.

Web storage is an API that provides a mechanism by which browsers can store key/value pairs locally within the user's browser, in a much more intuitive fashion than using cookies. The web storage provides two mechanisms for storing data on the client.

1️⃣ Local storage: It stores data for current origin with no expiration date.

2️⃣ Session storage: It stores data for one session and the data is lost when the browser tab is closed.

FeatureCookieLocal StorageSession Storage
Accessed on client or server sideBoth server-side & client-sideclient-side onlyclient-side only
LifetimeAs configured using Expires optionuntil deleteduntil tab is closed
SSL supportSupportedNot supportedNot supported
Maximum data size4KB5 MB5 MB

4. What is a storage event and its event handler

JS
window.onstorage = functionRef;

window.onstorage = function (e) {
  console.log(
    "The " +
      e.key +
      " key has been changed from " +
      e.oldValue +
      " to " +
      e.newValue +
      "."
  );
};

// check web storage browser support
if (typeof Storage !== "undefined") {
  // Code for localStorage/sessionStorage.
} else {
  // Sorry! No Web Storage support..
}

5. Web Worker Example

JS
let i = 0;

function timedCount() {
  i = i + 1;
  postMessage(i);
  setTimeout("timedCount()", 500);
}

timedCount();
JS
if (typeof w == "undefined") {
  w = new Worker("counter.js");
  w.onmessage = function (event) {
    document.getElementById("message").innerHTML = event.data;
  };

  w.terminate(); // Terminate a Web Worker
  w = undefined; // Reuse the Web Worker
}

6. What is a promise

A promise is an object that may produce a single value some time 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.

  • Pending: This is an initial state of the Promise before an operation begins
  • Fulfilled: This state indicates that the specified operation was completed.
  • Rejected: This state indicates that the operation did not complete. In this case an error value will be thrown.
JS
const promise = new Promise(function (resolve, reject) {
  // promise description
});

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

promise.then((value) => console.log(value));

7. Server-sent events / Notifications

The EventSource object is used to receive server-sent event notifications.

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

Check browser support for server-sent events.

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

events available for server sent events.

EventDescription
onopenIt is used when a connection to the server is opened
onmessageThis event is used when a message is received
onerrorIt happens when an error occurs

8. Promise.all() / Promise.race()

all()

Promise.all is a promise that takes an array of promises as an input (an iterable), and it gets resolved when all the promises get resolved or any one of them gets rejected.

JS
const p1 = new Promise((resolve,reject) => {
	setTimeout(resolve(1), 400)
})
const p2 = new Promise((resolve,reject) => {
	setTimeout(resolve(2), 200)
})
const p3 = new Promise((resolve,reject) => {
	setTimeout(resolve(3), 300)
})
Promise.all([p1,p2,p3]).then(res => {
	console.log(res)
})

Note: Remember that the order of the promises(output the result) is maintained as per input order.

race()

Promise.race() method will return the promise instance which is firstly resolved or rejected.

JS
var promise1 = new Promise(function (resolve, reject) {
  setTimeout(resolve, 500, "one");
});
var promise2 = new Promise(function (resolve, reject) {
  setTimeout(resolve, 100, "two");
});

Promise.race([promise1, promise2]).then(function (value) {
  console.log(value); // "two" // Both promises will resolve, but promise2 is faster
});

9. What is the difference between null and undefined

NullUndefined
It is an assignment value which indicates that variable points to no object.It is not an assignment value where a variable has been declared but has not yet been assigned a value.
Type of null is objectType of undefined is undefined
The null value is a primitive value that represents the null, empty, or non-existent reference.The undefined value is a primitive value used when a variable has not been assigned a value.
Indicates the absence of a value for a variableIndicates absence of variable itself
Converted to zero (0) while performing primitive operationsConverted to NaN while performing primitive operations

10. What is the difference between window and document

WindowDocument
It is the root level element in any web pageIt is the direct child of the window object. This is also known as Document Object Model (DOM)
By default window object is available implicitly in the pageYou can access it via window.document or document.
It has methods like alert(), confirm() and properties like document, locationIt provides methods like getElementById, getElementsByTagName, createElement etc