FrontendDeveloper.in

JavaScript Interview Questions

  • Question 377

    How do you create copy to clipboard button

    You need to select the content(using .select() method) of the input element and execute the copy command with execCommand (i.e, execCommand('copy')). You can also execute other system commands like cut and paste.

    document.querySelector("#copy-button").onclick = function () {
    // Select the content
    document.querySelector("#copy-input").select();
    // Copy to the clipboard
    document.execCommand("copy");
    };
    
  • Question 378

    What is the shortcut to get timestamp

    You can use new Date().getTime() to get the current timestamp. There is an alternative shortcut to get the value.

    console.log(+new Date());
    console.log(Date.now());
    
  • Question 379

    How do you flattening multi dimensional arrays

    Flattening bi-dimensional arrays is trivial with Spread operator.

    const biDimensionalArr = [11, [22, 33], [44, 55], [66, 77], 88, 99];
    const flattenArr = [].concat(...biDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
    

    But you can make it work with multi-dimensional arrays by recursive calls,

    function flattenMultiArray(arr) {
    const flattened = [].concat(...arr);
    return flattened.some((item) => Array.isArray(item))
    ? flattenMultiArray(flattened)
    : flattened;
    }
    const multiDimensionalArr = [
    11,
    [22, 33],
    [44, [55, 66, [77, [88]], 99]],
    ];
    const flatArr = flattenMultiArray(multiDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
    

    Also you can use the flat method of Array.

    const arr = [1, [2, 3], 4, 5, [6, 7]];
    const fllattenArr = arr.flat(); // [1, 2, 3, 4, 5, 6, 7]
    
    // And for multiDimensional arrays
    const multiDimensionalArr = [
    11,
    [22, 33],
    [44, [55, 66, [77, [88]], 99]],
    ];
    const oneStepFlat = multiDimensionalArr.flat(1); // [11, 22, 33, 44, [55, 66, [77, [88]], 99]]
    const towStep = multiDimensionalArr.flat(2); // [11, 22, 33, 44, 55, 66, [77, [88]], 99]
    const fullyFlatArray = multiDimensionalArr.flat(Infinity); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
    
  • Question 380

    What is the easiest multi condition checking

    You can use indexOf to compare input with multiple values instead of checking each value as one condition.

    // Verbose approach
    if (
    input === "first" ||
    input === 1 ||
    input === "second" ||
    input === 2
    ) {
    someFunction();
    }
    // Shortcut
    if (["first", 1, "second", 2].indexOf(input) !== -1) {
    someFunction();
    }
    
  • Question 381

    How do you capture browser back button

    The beforeunload event is triggered when the window, the document and its resources are about to be unloaded. This event is helpful to warn users about losing the current data and detect back button event.

    window.addEventListener("beforeunload", () => {
    console.log("Clicked browser back button");
    });
    

    You can also use popstate event to detect the browser back button. Note: The history entry has been activated using history.pushState method.

    window.addEventListener("popstate", () => {
    console.log("Clicked browser back button");
    box.style.backgroundColor = "white";
    });
    
    const box = document.getElementById("div");
    
    box.addEventListener("click", () => {
    box.style.backgroundColor = "blue";
    window.history.pushState({}, null, null);
    });
    

    In the preceeding code, When the box element clicked, its background color appears in blue color and changed to while color upon clicking the browser back button using popstate event handler. The state property of popstate contains the copy of history entry's state object.

  • Question 383

    What are wrapper objects

    Primitive Values like string,number and boolean don't have properties and methods but they are temporarily converted or coerced to an object(Wrapper object) when you try to perform actions on them. For example, if you apply toUpperCase() method on a primitive string value, it does not throw an error but returns uppercase of the string.

    let name = "john";
    
    console.log(name.toUpperCase()); // Behind the scenes treated as console.log(new String(name).toUpperCase());
    

    i.e, Every primitive except null and undefined have Wrapper Objects and the list of wrapper objects are String,Number,Boolean,Symbol and BigInt.

  • Question 384

    What is AJAX

    AJAX stands for Asynchronous JavaScript and XML and it is a group of related technologies(HTML, CSS, JavaScript, XMLHttpRequest API etc) used to display data asynchronously. i.e. We can send data to the server and get data from the server without reloading the web page.

  • Question 386

    How to cancel a fetch request

    Until a few days back, One shortcoming of native promises is no direct way to cancel a fetch request. But the new AbortController from js specification allows you to use a signal to abort one or multiple fetch calls. The basic flow of cancelling a fetch request would be as below,

    1. Create an AbortController instance
    2. Get the signal property of an instance and pass the signal as a fetch option for signal
    3. Call the AbortController's abort property to cancel all fetches that use that signal For example, passing the same signal to multiple fetch calls will cancel all requests with that signal,
    const controller = new AbortController();
    const { signal } = controller;
    
    fetch("http://localhost:8000", { signal })
    .then((response) => {
    console.log(`Request 1 is complete!`);
    })
    .catch((e) => {
    if (e.name === "AbortError") {
    // We know it's been canceled!
    }
    });
    
    fetch("http://localhost:8000", { signal })
    .then((response) => {
    console.log(`Request 2 is complete!`);
    })
    .catch((e) => {
    if (e.name === "AbortError") {
    // We know it's been canceled!
    }
    });
    
    // Wait 2 seconds to abort both requests
    setTimeout(() => controller.abort(), 2000);
    
  • Question 387

    What is web speech API

    Web speech API is used to enable modern browsers recognize and synthesize speech(i.e, voice data into web apps). This API was introduced by W3C Community in the year 2012. It has two main parts:

    1. SpeechRecognition (Asynchronous Speech Recognition or Speech-to-Text): It provides the ability to recognize voice context from an audio input and respond accordingly. This is accessed by the SpeechRecognition interface. The example below shows how to use this API to get text from speech,
    window.SpeechRecognition =
    window.webkitSpeechRecognition || window.SpeechRecognition; // webkitSpeechRecognition for Chrome and SpeechRecognition for FF
    const recognition = new window.SpeechRecognition();
    recognition.onresult = (event) => {
    // SpeechRecognitionEvent type
    const speechToText = event.results[0][0].transcript;
    console.log(speechToText);
    };
    recognition.start();
    

    In this API, browser is going to ask you for permission to use your microphone

    1. SpeechSynthesis (Text-to-Speech): It provides the ability to recognize voice context from an audio input and respond. This is accessed by the SpeechSynthesis interface. For example, the below code is used to get voice/speech from text,
    if ("speechSynthesis" in window) {
    var speech = new SpeechSynthesisUtterance("Hello World!");
    speech.lang = "en-US";
    window.speechSynthesis.speak(speech);
    }
    

    The above examples can be tested on chrome(33+) browser's developer console. Note: This API is still a working draft and only available in Chrome and Firefox browsers(ofcourse Chrome only implemented the specification)

  • Question 388

    What is minimum timeout throttling

    Both browser and NodeJS javascript environments throttles with a minimum delay that is greater than 0ms. That means even though setting a delay of 0ms will not happen instantaneously. Browsers: They have a minimum delay of 4ms. This throttle occurs when successive calls are triggered due to callback nesting(certain depth) or after a certain number of successive intervals. Note: The older browsers have a minimum delay of 10ms. Nodejs: They have a minimum delay of 1ms. This throttle happens when the delay is larger than 2147483647 or less than 1. The best example to explain this timeout throttling behavior is the order of below code snippet.

    function runMeFirst() {
    console.log("My script is initialized");
    }
    setTimeout(runMeFirst, 0);
    console.log("Script loaded");
    

    and the output would be in

    Script loaded
    My script is initialized
    

    If you don't use setTimeout, the order of logs will be sequential.

    function runMeFirst() {
    console.log("My script is initialized");
    }
    runMeFirst();
    console.log("Script loaded");
    

    and the output is,

    My script is initialized
    Script loaded
    
  • Question 390

    What are tasks in event loop

    A task is any javascript code/program which is scheduled to be run by the standard mechanisms such as initially starting to run a program, run an event callback, or an interval or timeout being fired. All these tasks are scheduled on a task queue. Below are the list of use cases to add tasks to the task queue,

    1. When a new javascript program is executed directly from console or running by the <script> element, the task will be added to the task queue.
    2. When an event fires, the event callback added to task queue
    3. When a setTimeout or setInterval is reached, the corresponding callback added to task queue
Get LinkedIn Premium at Rs 399