FrontendDeveloper.in

JavaScript Interview Questions

  • Question 46

    What is a storage event and its event handler

    The StorageEvent is an event that fires when a storage area has been changed in the context of another document. Whereas onstorage property is an EventHandler for processing storage events. The syntax would be as below

    window.onstorage = functionRef;
    

    Let's take the example usage of onstorage event handler which logs the storage key and it's values

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

    Why do you need web storage

    Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Also, the information is never transferred to the server. Hence this is a more recommended approach than Cookies.

  • Question 48

    How do you check web storage browser support

    You need to check browser support for localStorage and sessionStorage before using web storage,

    if (typeof Storage !== "undefined") {
    // Code for localStorage/sessionStorage.
    } else {
    // Sorry! No Web Storage support..
    }
    
  • Question 49

    How do you check web workers browser support

    You need to check browser support for web workers before using it

    if (typeof Worker !== "undefined") {
    // code for Web worker support.
    } else {
    // Sorry! No Web Worker support..
    }
    
  • Question 50

    Give an example of a web worker

    You need to follow below steps to start using web workers for counting example

    1. Create a Web Worker File: You need to write a script to increment the count value. Let's name it as counter.js
    let i = 0;
    
    function timedCount() {
    i = i + 1;
    postMessage(i);
    setTimeout("timedCount()", 500);
    }
    
    timedCount();
    

    Here postMessage() method is used to post a message back to the HTML page

    1. Create a Web Worker Object: You can create a web worker object by checking for browser support. Let's name this file as web_worker_example.js
    if (typeof w == "undefined") {
    w = new Worker("counter.js");
    }
    

    and we can receive messages from web worker

    w.onmessage = function (event) {
    document.getElementById("message").innerHTML = event.data;
    };
    
    1. Terminate a Web Worker: Web workers will continue to listen for messages (even after the external script is finished) until it is terminated. You can use the terminate() method to terminate listening to the messages.
    w.terminate();
    
    1. Reuse the Web Worker: If you set the worker variable to undefined you can reuse the code
    w = undefined;
    
  • Question 52

    What is a promise

    A Promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It acts as a placeholder for a value that may not be available yet but will be resolved in the future.

    A Promise can be in one of three states:

    • pending: Initial state, neither fulfilled nor rejected.
    • fulfilled: The operation completed successfully.
    • rejected: The operation failed (e.g., due to a network error).

    Promise Syntax

    const promise = new Promise(function (resolve, reject) {
    // Perform async operation
    });
    

    Example: Creating and Using a Promise

    const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
    resolve("I'm a Promise!");
    }, 5000);
    });
    
    promise
    .then((value) => console.log(value)) // Logs after 5 seconds: "I'm a Promise!"
    .catch((error) => console.error(error))  // Handles any rejection
    .finally(() => console.log("Done"));     // Runs regardless of success or failure
    

    In the above example:

    • A Promise is created to handle an asynchronous operation with resolve and reject callbacks.
    • The setTimeout resolves the promise with a value after 5 seconds.
    • .then(), .catch(), and .finally() are used to handle success, errors, and cleanup respectively.

    The action flow of a promise will be as below,

    Screenshot

  • Question 53

    Why do you need a promise

    Promises are used to handle asynchronous operations, especially in languages like JavaScript, which often work with non-blocking operations such as network requests, file I/O, and timers. When an operation is asynchronous, it doesn't immediately return a result; instead, it works in the background and provides the result later. Handling this in a clean, organized way can be difficult without a structured approach.

    Promises are used to:

    1. Handle asynchronous operations.
    2. Provide a cleaner alternative to callbacks.
    3. Avoid callback hell.
    4. Make code more readable and maintainable.
  • Question 54

    Explain the three states of promise

    Promises have three states:

    1. Pending: This is an initial state of the Promise before an operation begins
    2. Fulfilled: This state indicates that the specified operation was completed.
    3. Rejected: This state indicates that the operation did not complete. In this case an error value will be thrown.
  • Question 55

    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 callback function

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

    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 57

    What is a 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 58

    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/X updates, stock price updates, news feeds etc.

  • Question 59

    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 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 60

    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
    }
    
Get LinkedIn Premium at Rs 399