Skip to content

Latest commit

 

History

History
785 lines (547 loc) · 36.5 KB

File metadata and controls

785 lines (547 loc) · 36.5 KB

Table of Contents

No. Questions
41 What are the differences between cookie, local storage and session storage
42 What is the main difference between localStorage and sessionStorage
43 How do you access web storage
44 What are the methods available on session storage
45 What is a storage event and its event handler
46 Why do you need web storage
47 How do you check web storage browser support
48 How do you check web workers browser support
49 Give an example of a web worker
50 What are the restrictions of web workers on DOM
51 What is a promise
52 Why do you need a promise
53 What are the three states of promise
54 What is a callback function
55 Why do we need callbacks
56 What is a callback hell
57 What are server-sent events
58 How do you receive server-sent event notifications
59 How do you check browser support for server-sent events
60 What are the events available for server sent events
61 What are the main rules of promise
62 What is callback in callback
63 What is promise chaining
64 What is promise.all
65 What is the purpose of the race method in promise
66 What is a strict mode in javascript
67 Why do you need strict mode
68 How do you declare strict mode
69 What is the purpose of double exclamation
70 What is the purpose of the delete operator
71 What is typeof operator
72 What is undefined property
73 What is null value
74 What is the difference between null and undefined
75 What is eval
76 What is the difference between window and document
77 How do you access history in javascript
78 How do you detect caps lock key turned on or not
79 What is isNaN
80 What are the differences between undeclared and undefined variables
81 What are global variables
82 What are the problems with global variables
83 What is NaN property
84 What is the purpose of isFinite function
85 What is an event flow
86 What is event bubbling
87 What is event capturing
88 How do you submit a form using JavaScript
89 How do you find operating system details
90 What is the difference between document load and DOMContentLoaded events
  1. What are the differences between cookie, local storage and session storage

    Below are some of the differences between cookie, local storage and session storage,

    Feature Cookie Local storage Session storage
    Accessed on client or server side Both server-side & client-side client-side only client-side only
    Lifetime As configured using Expires option until deleted until tab is closed
    SSL support Supported Not supported Not supported
    Maximum data size 4KB 5 MB 5MB

    ⬆ Back to Top

  2. What is the main difference between localStorage and sessionStorage

    LocalStorage is the same as SessionStorage but it persists the data even when the browser is closed and reopened(i.e it has no expiration time) whereas in sessionStorage data gets cleared when the page session ends.

    ⬆ Back to Top

  3. How do you access web storage

    The Window object implements the WindowLocalStorage and WindowSessionStorage objects which has localStorage(window.localStorage) and sessionStorage(window.sessionStorage) properties respectively. These properties create an instance of the Storage object, through which data items can be set, retrieved and removed for a specific domain and storage type (session or local). For example, you can read and write on local storage objects as below

    localStorage.setItem("logo", document.getElementById("logo").value);
    localStorage.getItem("logo");

    ⬆ Back to Top

  4. What are the methods available on session storage

    The session storage provided methods for reading, writing and clearing the session data

    // Save data to sessionStorage
    sessionStorage.setItem("key", "value");
    
    // Get saved data from sessionStorage
    let data = sessionStorage.getItem("key");
    
    // Remove saved data from sessionStorage
    sessionStorage.removeItem("key");
    
    // Remove all saved data from sessionStorage
    sessionStorage.clear();

    ⬆ Back to Top

  5. 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 +
          "."
      );
    };

    ⬆ Back to Top

  6. 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.

    ⬆ Back to Top

  7. 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..
    }

    ⬆ Back to Top

  8. 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..
    }

    ⬆ Back to Top

  9. 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;

    ⬆ Back to Top

  10. What are the restrictions of web workers on DOM

    WebWorkers don't have access to below javascript objects since they are defined in an external files

    1. Window object
    2. Document object
    3. Parent object

    ⬆ Back to Top

  11. 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.

    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,

    Screenshot

    ⬆ Back to Top

  12. 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.

    ⬆ Back to Top

  13. What are 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.

    ⬆ Back to Top

  14. 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);

    ⬆ Back to Top

  15. 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.

    ⬆ Back to Top

  16. 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(){
                    ....
                });
            });
        });
    });

    ⬆ Back to Top

  17. 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.

    ⬆ Back to Top

  18. 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 + "<br>";
      };
    }

    ⬆ Back to Top

  19. 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
    }

    ⬆ Back to Top

  20. What are the events available for server sent events

    Below are the list of events available for server sent events

    Event Description
    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

    ⬆ Back to Top

  21. What are the main rules of promise

    A promise must follow a specific set of rules:

    1. A promise is an object that supplies a standard-compliant .then() method
    2. A pending promise may transition into either fulfilled or rejected state
    3. A fulfilled or rejected promise is settled and it must not transition into any other state.
    4. Once a promise is settled, the value must not change.

    ⬆ Back to Top

  22. What is callback in callback

    You can nest one callback inside in another callback to execute the actions sequentially one by one. This is known as callbacks in callbacks.

    loadScript("/script1.js", function (script) {
      console.log("first script is loaded");
    
      loadScript("/script2.js", function (script) {
        console.log("second script is loaded");
    
        loadScript("/script3.js", function (script) {
          console.log("third script is loaded");
          // after all scripts are loaded
        });
      });
    });

    ⬆ Back to Top

  23. What is promise chaining

    The process of executing a sequence of asynchronous tasks one after another using promises is known as Promise chaining. Let's take an example of promise chaining for calculating the final result,

    new Promise(function (resolve, reject) {
      setTimeout(() => resolve(1), 1000);
    })
      .then(function (result) {
        console.log(result); // 1
        return result * 2;
      })
      .then(function (result) {
        console.log(result); // 2
        return result * 3;
      })
      .then(function (result) {
        console.log(result); // 6
        return result * 4;
      });

    In the above handlers, the result is passed to the chain of .then() handlers with the below work flow,

    1. The initial promise resolves in 1 second,
    2. After that .then handler is called by logging the result(1) and then return a promise with the value of result * 2.
    3. After that the value passed to the next .then handler by logging the result(2) and return a promise with result * 3.
    4. Finally the value passed to the last .then handler by logging the result(6) and return a promise with result * 4.

    ⬆ Back to Top

  24. What is promise.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. For example, the syntax of promise.all method is below,

    Promise.all([Promise1, Promise2, Promise3]) .then(result) => {   console.log(result) }) .catch(error => console.log(`Error in promises ${error}`))

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

    ⬆ Back to Top

  25. What is the purpose of the race method in promise

    Promise.race() method will return the promise instance which is firstly resolved or rejected. Let's take an example of race() method where promise2 is resolved first

    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
    });

    ⬆ Back to Top

  26. What is a strict mode in javascript

    Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This way it prevents certain actions from being taken and throws more exceptions. The literal expression "use strict"; instructs the browser to use the javascript code in the Strict mode.

    ⬆ Back to Top

  27. Why do you need strict mode

    Strict mode is useful to write "secure" JavaScript by notifying "bad syntax" into real errors. For example, it eliminates accidentally creating a global variable by throwing an error and also throws an error for assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object.

    ⬆ Back to Top

  28. How do you declare strict mode

    The strict mode is declared by adding "use strict"; to the beginning of a script or a function. If declared at the beginning of a script, it has global scope.

    "use strict";
    x = 3.14; // This will cause an error because x is not declared

    and if you declare inside a function, it has local scope

    x = 3.14; // This will not cause an error.
    myFunction();
    
    function myFunction() {
      "use strict";
      y = 3.14; // This will cause an error
    }

    ⬆ Back to Top

  29. What is the purpose of double exclamation

    The double exclamation or negation(!!) ensures the resulting type is a boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, it will be true. For example, you can test IE version using this expression as below,

    let isIE8 = false;
    isIE8 = !!navigator.userAgent.match(/MSIE 8.0/);
    console.log(isIE8); // returns true or false

    If you don't use this expression then it returns the original value.

    console.log(navigator.userAgent.match(/MSIE 8.0/)); // returns either an Array or null

    Note: The expression !! is not an operator, but it is just twice of ! operator.

    ⬆ Back to Top

  30. What is the purpose of the delete operator

    The delete keyword is used to delete the property as well as its value.

    var user = { name: "John", age: 20 };
    delete user.age;
    
    console.log(user); // {name: "John"}

    ⬆ Back to Top

  31. What is typeof operator

    You can use the JavaScript typeof operator to find the type of a JavaScript variable. It returns the type of a variable or an expression.

    typeof "John Abraham"; // Returns "string"
    typeof (1 + 2); // Returns "number"
    typeof [1, 2, 3] // Returns "object" because all arrays are also objects

    ⬆ Back to Top

  32. What is undefined property

    The undefined property indicates that a variable has not been assigned a value, or declared but not initialized at all. The type of undefined value is undefined too.

    var user; // Value is undefined, type is undefined
    console.log(typeof user); //undefined

    Any variable can be emptied by setting the value to undefined.

    user = undefined;

    ⬆ Back to Top

  33. What is null value

    The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values. The type of null value is object. You can empty the variable by setting the value to null.

    var user = null;
    console.log(typeof user); //object

    ⬆ Back to Top

  34. What is the difference between null and undefined

    Below are the main differences between null and undefined,

    Null Undefined
    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 object Type 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 variable Indicates absence of variable itself
    Converted to zero (0) while performing primitive operations Converted to NaN while performing primitive operations

    ⬆ Back to Top

  35. What is eval

    The eval() function evaluates JavaScript code represented as a string. The string can be a JavaScript expression, variable, statement, or sequence of statements.

    console.log(eval("1 + 2")); //  3

    ⬆ Back to Top

  36. What is the difference between window and document

    Below are the main differences between window and document,

    Window Document
    It is the root level element in any web page It 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 page You can access it via window.document or document.
    It has methods like alert(), confirm() and properties like document, location It provides methods like getElementById, getElementsByTagName, createElement etc

    ⬆ Back to Top

  37. How do you access history in javascript

    The window.history object contains the browser's history. You can load previous and next URLs in the history using back() and next() methods.

    function goBack() {
      window.history.back();
    }
    function goForward() {
      window.history.forward();
    }

    Note: You can also access history without window prefix.

    ⬆ Back to Top

  38. How do you detect caps lock key turned on or not

    The mouseEvent getModifierState() is used to return a boolean value that indicates whether the specified modifier key is activated or not. The modifiers such as CapsLock, ScrollLock and NumLock are activated when they are clicked, and deactivated when they are clicked again.

    Let's take an input element to detect the CapsLock on/off behavior with an example,

    <input type="password" onmousedown="enterInput(event)" />
    
    <p id="feedback"></p>
    
    <script>
      function enterInput(e) {
        var flag = e.getModifierState("CapsLock");
        if (flag) {
          document.getElementById("feedback").innerHTML = "CapsLock activated";
        } else {
          document.getElementById("feedback").innerHTML =
            "CapsLock not activated";
        }
      }
    </script>

    ⬆ Back to Top

  39. What is isNaN

    The isNaN() function is used to determine whether a value is an illegal number (Not-a-Number) or not. i.e, This function returns true if the value equates to NaN. Otherwise it returns false.

    isNaN("Hello"); //true
    isNaN("100"); //false

    ⬆ Back to Top

  40. What are the differences between undeclared and undefined variables

    Below are the major differences between undeclared(not defined) and undefined variables,

    undeclared undefined
    These variables do not exist in a program and are not declared These variables declared in the program but have not assigned any value
    If you try to read the value of an undeclared variable, then a runtime error is encountered If you try to read the value of an undefined variable, an undefined value is returned.

    ⬆ Back to Top

  41. What are global variables

    Global variables are those that are available throughout the length of the code without any scope. The var keyword is used to declare a local variable but if you omit it then it will become global variable

    msg = "Hello"; // var is missing, it becomes global variable

    ⬆ Back to Top

  42. What are the problems with global variables

    The problem with global variables is the conflict of variable names of local and global scope. It is also difficult to debug and test the code that relies on global variables.

    ⬆ Back to Top

  43. What is NaN property

    The NaN property is a global property that represents "Not-a-Number" value. i.e, It indicates that a value is not a legal number. It is very rare to use NaN in a program but it can be used as return value for few cases

    Math.sqrt(-1);
    parseInt("Hello");

    ⬆ Back to Top

  44. What is the purpose of isFinite function

    The isFinite() function is used to determine whether a number is a finite, legal number. It returns false if the value is +infinity, -infinity, or NaN (Not-a-Number), otherwise it returns true.

    isFinite(Infinity); // false
    isFinite(NaN); // false
    isFinite(-Infinity); // false
    
    isFinite(100); // true

    ⬆ Back to Top

  45. What is an event flow

    Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event for each of its parent elements first, starting at the top with the global window object. There are two ways of event flow

    1. Top to Bottom(Event Capturing)
    2. Bottom to Top (Event Bubbling)

    ⬆ Back to Top

  46. What is event bubbling

    Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element.

    ⬆ Back to Top

  47. What is event capturing

    Event capturing is a type of event propagation where the event is first captured by the outermost element, and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the innermost DOM element.

    ⬆ Back to Top

  48. How do you submit a form using JavaScript

    You can submit a form using document.forms[0].submit(). All the form input's information is submitted using onsubmit event handler

    function submit() {
      document.forms[0].submit();
    }

    ⬆ Back to Top

  49. How do you find operating system details

    The window.navigator object contains information about the visitor's browser OS details. Some of the OS properties are available under platform property,

    console.log(navigator.platform);

    ⬆ Back to Top

  50. What is the difference between document load and DOMContentLoaded events

    The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for assets(stylesheets, images, and subframes) to finish loading. Whereas The load event is fired when the whole page has loaded, including all dependent resources(stylesheets, images).

    ⬆ Back to Top