FrontendDeveloper.in

JavaScript Interview Questions

  • Question 391

    What is microtask

    A microtask is a type of JavaScript callback that is scheduled to run immediately after the currently executing script and before the next event loop tick. Microtasks are executed after the current task completes and before any new tasks (macrotasks) are run. This ensures a fast and predictable update cycle.

    Common sources of microtasks stored in the microtask queue include:

    1. Promises: When a Promise is resolved or rejected, its .then(), .catch(), and .finally() callbacks are placed in the microtask queue.
    Promise.resolve().then(() => {
     console.log('Microtask from a Promise');
    });
    
    1. queueMicrotask():

    A method that explicitly schedules a function to be run in the microtask queue.

    queueMicrotask(() => {
    console.log('Microtask from  queueMicrotask');
     });
    
    1. MutationObserver callbacks:

    Observers changes in the DOM and triggers a callback as a microtask.

    const observer = new MutationObserver(() => {
    console.log('Microtask from MutationObserver');
    })
    observer.observe(document.body, {childList: true});
    
    1. await: Await internally uses Promises, so the code after await is scheduled as a microtask.
    async function asyncFunction() {
    await null;
    console.log('Microtask from Await'); // Schedule this code as microtask
    }
    

    Note: All of these microtasks are processed in the same turn of the event loop.

  • Question 392

    What are different event loops

    In JavaScript, there are multiple event loops that can be used depending on the context of your application. The most common event loops are:

    1. The Browser Event Loop
    2. The Node.js Event Loop
    • Browser Event Loop: The Browser Event Loop is used in client-side JavaScript applications and is responsible for handling events that occur within the browser environment, such as user interactions (clicks, keypresses, etc.), HTTP requests, and other asynchronous actions.

    • The Node.js Event Loop is used in server-side JavaScript applications and is responsible for handling events that occur within the Node.js runtime environment, such as file I/O, network I/O, and other asynchronous actions.

  • Question 393

    What is the purpose of queueMicrotask

    The queueMicrotask function is used to schedule a microtask, which is a function that will be executed asynchronously in the microtask queue. The purpose of queueMicrotask is to ensure that a function is executed after the current task has finished, but before the browser performs any rendering or handles user events.

    Example:

    console.log("Start"); //1
    
    queueMicrotask(() => {
    console.log("Inside microtask"); // 3
    });
    
    console.log("End"); //2
    

    By using queueMicrotask, you can ensure that certain tasks or callbacks are executed at the earliest opportunity during the JavaScript event loop, making it useful for performing work that needs to be done asynchronously but with higher priority than regular setTimeout or setInterval callbacks.

  • Question 394

    How do you use javascript libraries in typescript file

    It is known that not all JavaScript libraries or frameworks have TypeScript declaration files. But if you still want to use libraries or frameworks in your TypeScript files without getting compilation errors, the only solution is declare keyword along with a variable declaration. For example, let's imagine you have a library called customLibrary that doesn’t have a TypeScript declaration and have a namespace called customLibrary in the global namespace. You can use this library in typescript code as below,

    declare var customLibrary;
    

    In the runtime, typescript will provide the type to the customLibrary variable as any type. The another alternative without using declare keyword is below

    var customLibrary: any;
    
  • Question 395

    What are the differences between promises and observables

    Some of the major difference in a tabular form

    PromisesObservables
    Emits only a single value at a timeEmits multiple values over a period of time(stream of values ranging from 0 to multiple)
    Eager in nature; they are going to be called immediatelyLazy in nature; they require subscription to be invoked
    Promise is always asynchronous even though it resolved immediatelyObservable can be either synchronous or asynchronous
    Doesn't provide any operatorsProvides operators such as map, forEach, filter, reduce, retry, and retryWhen etc
    Cannot be canceledCanceled by using unsubscribe() method
  • Question 396

    What is heap

    Heap(Or memory heap) is the memory location where objects are stored when we define variables. i.e, This is the place where all the memory allocations and de-allocation take place. Both heap and call-stack are two containers of JS runtime. Whenever runtime comes across variables and function declarations in the code it stores them in the Heap.

    Screenshot

  • Question 397

    What is an event table

    Event Table is a data structure that stores and keeps track of all the events which will be executed asynchronously like after some time interval or after the resolution of some API requests. i.e Whenever you call a setTimeout function or invoke async operation, it is added to the Event Table. It doesn't not execute functions on it’s own. The main purpose of the event table is to keep track of events and send them to the Event Queue as shown in the below diagram.

    Screenshot

  • Question 398

    What is a microTask queue

    Microtask Queue is the new queue where all the tasks initiated by promise objects get processed before the callback queue. The microtasks queue are processed before the next rendering and painting jobs. But if these microtasks are running for a long time then it leads to visual degradation.

  • Question 399

    What is the difference between shim and polyfill

    A shim is a library that brings a new API to an older environment, using only the means of that environment. It isn't necessarily restricted to a web application. For example, es5-shim.js is used to emulate ES5 features on older browsers (mainly pre IE9). Whereas polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. In a simple sentence, a polyfill is a shim for a browser API.

  • Question 400

    How do you detect primitive or non primitive value type

    In JavaScript, primitive types include boolean, string, number, BigInt, null, Symbol and undefined. Whereas non-primitive types include the Objects. But you can easily identify them with the below function,

    var myPrimitive = 30;
    var myNonPrimitive = {};
    function isPrimitive(val) {
    return Object(val) !== val;
    }
    
    isPrimitive(myPrimitive);
    isPrimitive(myNonPrimitive);
    

    If the value is a primitive data type, the Object constructor creates a new wrapper object for the value. But If the value is a non-primitive data type (an object), the Object constructor will give the same object.

  • Question 401

    What is babel

    Babel is a JavaScript transpiler to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Some of the main features are listed below,

    1. Transform syntax
    2. Polyfill features that are missing in your target environment (using @babel/polyfill)
    3. Source code transformations (or codemods)
  • Question 402

    Is Node.js completely single threaded

    Node is a single thread, but some of the functions included in the Node.js standard library(e.g, fs module functions) are not single threaded. i.e, Their logic runs outside of the Node.js single thread to improve the speed and performance of a program.

  • Question 404

    What is RxJS

    RxJS (Reactive Extensions for JavaScript) is a library for implementing reactive programming using observables that makes it easier to compose asynchronous or callback-based code. It also provides utility functions for creating and working with observables.

  • Question 405

    What is the difference between Function constructor and function declaration

    The functions which are created with Function constructor do not create closures to their creation contexts but they are always created in the global scope. i.e, the function can access its own local variables and global scope variables only. Whereas function declarations can access outer function variables(closures) too.

    Let's see this difference with an example,

    Function Constructor:

    var a = 100;
    function createFunction() {
    var a = 200;
    return new Function("return a;");
    }
    console.log(createFunction()()); // 100
    

    Function declaration:

    var a = 100;
    function createFunction() {
    var a = 200;
    return function func() {
    return a;
    };
    }
    console.log(createFunction()()); // 200
    
Get LinkedIn Premium at Rs 399