devd123 / important-javascript-interview-questions

Find most important interview questions for JavaScript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

  1. What are the possible ways to create objects in JavaScript

    There are many ways to create objects in javascript as below

    1. Object constructor:

      The simplest way to create an empty object is using the Object constructor. Currently this approach is not recommended.

      var object = new Object();
    2. Object's create method:

      The create method of Object creates a new object by passing the prototype object as a parameter

      var object = Object.create(null);
    3. Object literal syntax:

      The object literal syntax is equivalent to create method when it passes null as parameter

      var object = {};
    4. Function constructor:

      Create any function and apply the new operator to create object instances,

      function Person(name){
         this.name=name;
         this.age=21;
      }
      var object = new Person("Sudheer");
    5. Function constructor with prototype:

      This is similar to function constructor but it uses prototype for their properties and methods,

      function Person(){}
      Person.prototype.name = "Sudheer";
      var object = new Person();

      This is equivalent to an instance created with an object create method with a function prototype and then call that function with an instance and parameters as arguments.

      function func {};
      

      new func(x, y, z);

      <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w" value="function func {};

      new func(x, y, z); " tabindex="0" role="button">

      (OR)

      // Create a new instance using function prototype.
      var newInstance = Object.create(func.prototype)
      

      // Call the function var result = func.call(newInstance, x, y, z),

      // If the result is a non-null object then use it otherwise just use the new instance. console.log(result && typeof result === 'object' ? result : newInstance);

      <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w" value="// Create a new instance using function prototype. var newInstance = Object.create(func.prototype)

      // Call the function var result = func.call(newInstance, x, y, z),

      // If the result is a non-null object then use it otherwise just use the new instance. console.log(result && typeof result === 'object' ? result : newInstance); " tabindex="0" role="button">

    6. ES6 Class syntax:

      ES6 introduces class feature to create the objects

      class Person {
         constructor(name) {
            this.name = name;
         }
      }
      

      var object = new Person("Sudheer");

      <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w" value="class Person { constructor(name) { this.name = name; } }

      var object = new Person("Sudheer"); " tabindex="0" role="button">

    7. Singleton pattern:

      A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance and this way one can ensure that they don't accidentally create multiple instances.

      var object = new function(){
         this.name = "Sudheer";
      }

      ⬆ Back to Top

  2. What is the purpose of the array slice method

    The slice() method returns the selected elements in an array as a new array object. It selects the elements starting at the given start argument, and ends at the given optional end argument without including the last element. If you omit the second argument then it selects till the end.

    Some of the examples of this method are,

    let arrayIntegers = [1, 2, 3, 4, 5];
    let arrayIntegers1 = arrayIntegers.slice(0,2); // returns [1,2]
    let arrayIntegers2 = arrayIntegers.slice(2,3); // returns [3]
    let arrayIntegers3 = arrayIntegers.slice(4); //returns [5]

    Note: Slice method won't mutate the original array but it returns the subset as a new array.

    ⬆ Back to Top

  3. What is the purpose of the array splice method

    The splice() method is used either adds/removes items to/from an array, and then returns the removed item. The first argument specifies the array position for insertion or deletion whereas the optional second argument indicates the number of elements to be deleted. Each additional argument is added to the array.

    Some of the examples of this method are,

    let arrayIntegersOriginal1 = [1, 2, 3, 4, 5];
    let arrayIntegersOriginal2 = [1, 2, 3, 4, 5];
    let arrayIntegersOriginal3 = [1, 2, 3, 4, 5];
    

    let arrayIntegers1 = arrayIntegersOriginal1.splice(0,2); // returns [1, 2]; original array: [3, 4, 5] let arrayIntegers2 = arrayIntegersOriginal2.splice(3); // returns [4, 5]; original array: [1, 2, 3] let arrayIntegers3 = arrayIntegersOriginal3.splice(3, 1, "a", "b", "c"); //returns [4]; original array: [1, 2, 3, "a", "b", "c", 5]

    <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w" value="let arrayIntegersOriginal1 = [1, 2, 3, 4, 5]; let arrayIntegersOriginal2 = [1, 2, 3, 4, 5]; let arrayIntegersOriginal3 = [1, 2, 3, 4, 5];

    let arrayIntegers1 = arrayIntegersOriginal1.splice(0,2); // returns [1, 2]; original array: [3, 4, 5] let arrayIntegers2 = arrayIntegersOriginal2.splice(3); // returns [4, 5]; original array: [1, 2, 3] let arrayIntegers3 = arrayIntegersOriginal3.splice(3, 1, "a", "b", "c"); //returns [4]; original array: [1, 2, 3, "a", "b", "c", 5] " tabindex="0" role="button">

    Note: Splice method modifies the original array and returns the deleted array.

    ⬆ Back to Top

  4. What is the difference between slice and splice

    Some of the major difference in a tabular form

    Slice Splice
    Doesn't modify the original array(immutable) Modifies the original array(mutable)
    Returns the subset of original array Returns the deleted elements as array
    Used to pick the elements from array Used to insert or delete elements to/from array

    ⬆ Back to Top

  5. What is a higher order function

    Higher-order function is a function that accepts another function as an argument or returns a function as a return value or both.

    const firstOrderFunc = () => console.log ('Hello, I am a First order function');
    const higherOrder = ReturnFirstOrderFunc => ReturnFirstOrderFunc();
    higherOrder(firstOrderFunc);

    ⬆ Back to Top

  6. What is the currying function

    Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. Currying is named after a mathematician Haskell Curry. By applying currying, a n-ary function turns it into a unary function.

    Let's take an example of n-ary function and how it turns into a currying function,

    const multiArgFunction = (a, b, c) => a + b + c;
    console.log(multiArgFunction(1,2,3));// 6
    

    const curryUnaryFunction = a => b => c => a + b + c; curryUnaryFunction (1); // returns a function: b => c => 1 + b + c curryUnaryFunction (1) (2); // returns a function: c => 3 + c curryUnaryFunction (1) (2) (3); // returns the number 6

    <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w" value="const multiArgFunction = (a, b, c) => a + b + c; console.log(multiArgFunction(1,2,3));// 6

    const curryUnaryFunction = a => b => c => a + b + c; curryUnaryFunction (1); // returns a function: b => c => 1 + b + c curryUnaryFunction (1) (2); // returns a function: c => 3 + c curryUnaryFunction (1) (2) (3); // returns the number 6 " tabindex="0" role="button">

    Curried functions are great to improve code reusability and functional composition.

    ⬆ Back to Top

  7. What is the difference between let and var

    You can list out the differences in a tabular format

    var let
    It is been available from the beginning of JavaScript Introduced as part of ES6
    It has function scope It has block scope
    Variables will be hoisted Hoisted but not initialized

    Let's take an example to see the difference,

    function userDetails(username) {
       if(username) {
         console.log(salary); // undefined due to hoisting
         console.log(age); // ReferenceError: Cannot access 'age' before initialization
         let age = 30;
         var salary = 10000;
       }
       console.log(salary); //10000 (accessible to due function scope)
       console.log(age); //error: age is not defined(due to block scope)
    }
    userDetails('John');

    ⬆ Back to Top

  8. What is Hoisting

    Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Remember that JavaScript only hoists declarations, not initialisation. Let's take a simple example of variable hoisting,

    console.log(message); //output : undefined
    var message = 'The variable Has been hoisted';

    The above code looks like as below to the interpreter,

    var message;
    console.log(message);
    message = 'The variable Has been hoisted';

    ⬆ Back to Top

  9. What are closures

    A closure is the combination of a function and the lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables. The closure has three scope chains

    1. Own scope where variables defined between its curly brackets
    2. Outer function’s variables
    3. Global variables

    Let's take an example of closure concept,

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

    As per the above code, the inner function(i.e, greetingInfo) has access to the variables in the outer function scope(i.e, Welcome) even after the outer function has returned.

    ⬆ Back to Top

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

    ⬆ Back to Top

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

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

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

    <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w" value="const promise = new Promise(resolve => { setTimeout(() => { resolve("I'm a Promise!"); }, 5000); }, reject => {

    });

    promise.then(value => console.log(value)); " tabindex="0" role="button">

    The action flow of a promise will be as below,

    Screenshot

    ⬆ Back to Top

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

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

    });

    <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w" value="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;

    }); " tabindex="0" role="button">

    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

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

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

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

    <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w" value="x = 3.14; // This will not cause an error. myFunction();

    function myFunction() { "use strict"; y = 3.14; // This will cause an error } " tabindex="0" role="button">

    ⬆ Back to Top

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

  20. What are the pros and cons of promises over callbacks

    Below are the list of pros and cons of promises over callbacks,

    Pros:

    1. It avoids callback hell which is unreadable
    2. Easy to write sequential asynchronous code with .then()
    3. Easy to write parallel asynchronous code with Promise.all()
    4. Solves some of the common problems of callbacks(call the callback too late, too early, many times and swallow errors/exceptions)

    Cons:

    1. It makes little complex code
    2. You need to load a polyfill if ES6 is not supported

    ⬆ Back to Top

  21. What is the difference between an attribute and a property

    Attributes are defined on the HTML markup whereas properties are defined on the DOM. For example, the below HTML element has 2 attributes type and value,

    <input type="text" value="Name:">

    You can retrieve the attribute value as below,

    const input = document.querySelector('input');
    console.log(input.getAttribute('value')); // Good morning
    console.log(input.value); // Good morning

    And after you change the value of the text field to "Good evening", it becomes like

    console.log(input.getAttribute('value')); // Good morning
    console.log(input.value); // Good evening

    ⬆ Back to Top

  22. What is an event loop

    The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't start processing the event loop until the async function has finished executing the code. Note: It allows Node.js to perform non-blocking I/O operations even though JavaScript is single-threaded.

    ⬆ Back to Top

  23. What is call stack

    Call Stack is a data structure for javascript interpreters to keep track of function calls in the program. It has two major actions,

    1. Whenever you call a function for its execution, you are pushing it to the stack.
    2. Whenever the execution is completed, the function is popped out of the stack.

    Let's take an example and it's state representation in a diagram format

    function hungry() {
       eatFruits();
    }
    function eatFruits() {
       return "I'm eating fruits";
    }
    

    // Invoke the hungry function hungry();

    <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w" value="function hungry() { eatFruits(); } function eatFruits() { return "I'm eating fruits"; }

    // Invoke the hungry function hungry(); " tabindex="0" role="button">

    The above code processed in a call stack as below,

    1. Add the hungry() function to the call stack list and execute the code.
    2. Add the eatFruits() function to the call stack list and execute the code.
    3. Delete the eatFruits() function from our call stack list.
    4. Delete the hungry() function from the call stack list since there are no items anymore.

    Screenshot

    ⬆ Back to Top

About

Find most important interview questions for JavaScript