Examness
\n```\n\n \n ↥ back to top"}},{"@type":"Question","name":"What are the recommendations to create new object?","acceptedAnswer":{"@type":"Answer","text":"It is recommended to avoid creating new objects using `new Object()`. Instead you can initialize values based on it is type to create the objects.\n\n* Assign {} instead of new Object()\n* Assign \"\" instead of new String()\n* Assign 0 instead of new Number()\n* Assign false instead of new Boolean()\n* Assign [] instead of new Array()\n* Assign /()/ instead of new RegExp()\n* Assign function (){} instead of new Function()\n\n**Example:**\n\n```js\nlet obj1 = {};\nlet obj2 = \"\";\nlet obj3 = 0;\nlet obj4 = false;\nlet obj5 = [];\nlet obj6 = /()/;\nlet obj7 = function(){};\n```\n\n \n ↥ back to top"}},{"@type":"Question","name":"What is event capturing?","acceptedAnswer":{"@type":"Answer","text":"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 inner DOM element.\n\n**Example:**\n\n```html\n
\n Article Element\n
\n DIV Element\n

\n P Element\n

\n
\n
\n\n\n```\n\n**⚝ Try this example on CodeSandbox**\n\n \n ↥ back to top"}},{"@type":"Question","name":"What is the purpose of clearTimeout method?","acceptedAnswer":{"@type":"Answer","text":"The `clearTimeout()` function is used in javascript to clear the timeout which has been set by `setTimeout()` function before that. i.e, The return value of setTimeout() function is stored in a variable and it\\'s passed into the `clearTimeout()` function to clear the timer.\n\nFor example, the below setTimeout method is used to display the message after 3 seconds. This timeout can be cleared by clearTimeout() method.\n\n```js\n// clearTimeout()\n\nvar msg;\nfunction greeting() {\n console.log(\"Hello World!\");\n stop();\n}\nfunction start() {\n console.log(\"start\");\n msg = setTimeout(greeting, 3000);\n}\nfunction stop() {\n console.log(\"stop\");\n clearTimeout(msg);\n}\n\nstart();\n\n// Output\nStart\nHello World!\nStop\n```\n\n**⚝ Try this example on CodeSandbox**\n\n \n ↥ back to top"}},{"@type":"Question","name":"What is the use of setTimeout?","acceptedAnswer":{"@type":"Answer","text":"The `setTimeout()` method is used to call a function or evaluates an expression after a specified number of milliseconds.\n\n**Syntax:**\n\n```js\nsetTimeout(callback function, delay in milliseconds)\n```\n\n**Example:**\n\n```js\nsetTimeout(() => {\n console.log(\"Delayed for 1 second.\");\n}, \"1000\")\n```\n\n \n ↥ back to top"}},{"@type":"Question","name":"What is a unary function?","acceptedAnswer":{"@type":"Answer","text":"Unary function (i.e. monadic) is a function that accepts exactly one argument. It stands for single argument accepted by a function.\n\n```js\n// Unary function\nconst unaryFunction = (number) => number + 10;\n\nconsole.log(unaryFunction(10)); // 20\n```\n\n**⚝ Try this example on CodeSandbox**\n\n \n ↥ back to top"}},{"@type":"Question","name":"What is the 'this keyword' and how does its context change?","acceptedAnswer":{"@type":"Answer","text":"In JavaScript, the context of **`this`** refers to the execution context, typically an object that owns the function where `this` is used.\n\n### 'this' in the Global Scope\n\nIn **non-strict** mode, `this` in the global scope refers to the `window` object. In **strict** mode, `this` is `undefined`.\n\n### 'this' in Functions\n\nIn **non-arrow functions**, the value of `this` depends on how the function is **invoked**. When invoked:\n\n- As a method of an object: `this` is the object.\n- Alone: In a browser, `this` is `window` or `global` in Node.js. In strict mode, it's `undefined`.\n- With `call`, `apply`, or `bind`: `this` is explicitly set.\n- As a constructor (with `new`): `this` is the newly created object.\n\n### 'this' in Arrow Functions\n\nArrow functions have a **fixed context** for `this` defined at **function creation** and are not changed by how they are invoked.\n\n- They do **not have** their own `this`.\n- They use the `this` from their surrounding lexical context (the enclosing function or global context).\n\n### Code Example: Global Context\n\nHere is the JavaScript code:\n\n```javascript\n// Main\nlet globalVar = 10;\n\nfunction globalFunction() {\n console.log('Global this: ', this.globalV"}},{"@type":"Question","name":"What is recursion in JavaScript?","acceptedAnswer":{"@type":"Answer","text":"**Recursion** is a technique in which a function calls itself until it reaches a base case (a condition that stops further calls). Every recursive function must have a base case to avoid infinite loops and stack overflow errors.\n\n**Example 01:** Factorial\n\n```js\nfunction factorial(n) {\n if (n <= 1) return 1; // base case\n return n * factorial(n - 1); // recursive call\n}\n\nconsole.log(factorial(5)); // 120 (5 × 4 × 3 × 2 × 1)\nconsole.log(factorial(0)); // 1\n```\n\n**Example 02:** Fibonacci\n\n```js\nfunction fibonacci(n) {\n if (n <= 1) return n;\n return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\nconsole.log(fibonacci(6)); // 8 (0, 1, 1, 2, 3, 5, 8)\n```\n\n**Example 03:** Flatten a nested array\n\n```js\nfunction flattenArray(arr) {\n return arr.reduce((acc, val) =>\n Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val),\n []);\n}\n\nconsole.log(flattenArray([1, [2, [3, [4]], 5]])); // [1, 2, 3, 4, 5]\n```\n\n**Recursion vs Iteration**:\n\n* Recursion is more readable for **tree/graph traversal, nested structures, and divide-and-conquer** problems\n* Iteration is more performant for **simple loops** — use it when recursion depth could be large\n\n*Note: For deeply nested structur"}}]}

Programming

JavaScript इंटरव्यू प्रश्न

Closures, prototypes, async, the event loop and ES features.

368 प्रश्न

  1. 1.

    What is an error object?

    शुरुआती

    An error object is a built in error object that provides error information when an error occurs. It has two properties: name and message.

    Example:

    try {
      greeting("Welcome");
    }
    catch(err) {
      console.log(err.name + ": " + err.message);
    }
    
    // Output
    ReferenceError: greeting is not defined

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  2. 2.

    What is the difference between get and defineProperty?

    शुरुआती

    Both has similar results until unless you use classes. If you use get the property will be defined on the prototype of the object whereas using Object.defineProperty() the property will be defined on the instance it is applied to.

    ↥ back to top

  3. 3.

    What is the use of stopPropagation method?

    शुरुआती

    The stopPropagation method is used to stop the event from bubbling up the event chain.

    For example, the below nested divs with stopPropagation method prevents default event propagation when clicking on nested div(Div1)

    <p>Click DIV1 Element</p>
    <div onclick="secondFunc()">DIV 2
      <div onclick="firstFunc(event)">DIV 1</div>
    </div>
    
    <script>
    function firstFunc(event) {
      alert("DIV 1");
      event.stopPropagation();
    }
    
    function secondFunc() {
      alert("DIV 2");
    }
    </script>

    ↥ back to top

  4. 4.

    What are the recommendations to create new object?

    शुरुआती

    It is recommended to avoid creating new objects using new Object(). Instead you can initialize values based on it is type to create the objects.

    • Assign {} instead of new Object()
    • Assign "" instead of new String()
    • Assign 0 instead of new Number()
    • Assign false instead of new Boolean()
    • Assign [] instead of new Array()
    • Assign /()/ instead of new RegExp()
    • Assign function (){} instead of new Function()

    Example:

    let obj1 = {};
    let obj2 = "";
    let obj3 = 0;
    let obj4 = false;
    let obj5 = [];
    let obj6 = /()/;
    let obj7 = function(){};

    ↥ back to top

  5. 5.

    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 inner DOM element.

    Example:

    <article id="ancestor">
        Article Element
        <div id="parent">
          DIV Element
          <p id="child">
            P Element
          </p>
        </div>
    </article>
    
    <script>
      // Script to click event handler to capture on each element
      for (let elem of document.querySelectorAll("*")) {
        elem.addEventListener(
          "click",
          (e) => console.log("Capturing:", elem.tagName),
          true
        );
      }
    </script>

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  6. 6.

    What is the purpose of clearTimeout method?

    शुरुआती

    The clearTimeout() function is used in javascript to clear the timeout which has been set by setTimeout() function before that. i.e, The return value of setTimeout() function is stored in a variable and it\'s passed into the clearTimeout() function to clear the timer.

    For example, the below setTimeout method is used to display the message after 3 seconds. This timeout can be cleared by clearTimeout() method.

    // clearTimeout()
    
    var msg;
    function greeting() {
      console.log("Hello World!");
      stop();
    }
    function start() {
      console.log("start");
      msg = setTimeout(greeting, 3000);
    }
    function stop() {
      console.log("stop");
      clearTimeout(msg);
    }
    
    start();
    
    // Output
    Start
    Hello World!
    Stop

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  7. 7.

    What is the use of setTimeout?

    शुरुआती

    The setTimeout() method is used to call a function or evaluates an expression after a specified number of milliseconds.

    Syntax:

    setTimeout(callback function, delay in milliseconds)

    Example:

    setTimeout(() => {
      console.log("Delayed for 1 second.");
    }, "1000")

    ↥ back to top

  8. 8.

    What is a unary function?

    शुरुआती

    Unary function (i.e. monadic) is a function that accepts exactly one argument. It stands for single argument accepted by a function.

    // Unary function
    const unaryFunction = (number) => number + 10;
    
    console.log(unaryFunction(10)); // 20

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  9. 9.

    What is the 'this keyword' and how does its context change?

    शुरुआती

    In JavaScript, the context of `this` refers to the execution context, typically an object that owns the function where this is used.

    'this' in the Global Scope

    In non-strict mode, this in the global scope refers to the window object. In strict mode, this is undefined.

    'this' in Functions

    In non-arrow functions, the value of this depends on how the function is invoked. When invoked:

    • As a method of an object: this is the object.
    • Alone: In a browser, this is window or global in Node.js. In strict mode, it's undefined.
    • With call, apply, or bind: this is explicitly set.
    • As a constructor (with new): this is the newly created object.

    'this' in Arrow Functions

    Arrow functions have a fixed context for this defined at function creation and are not changed by how they are invoked.

    • They do not have their own this.
    • They use the this from their surrounding lexical context (the enclosing function or global context).

    Code Example: Global Context

    Here is the JavaScript code:

    // Main
    let globalVar = 10;
    
    function globalFunction() {
        console.log('Global this: ', this.globalVar);
        console.log('Global this in strict mode: ', this);
    }
    
    globalFunction();  // Output: 10, window or undefined (in strict mode)
    
    // In Node.js, it will be different, because "window" is not defined. But "this" will refer to the global object.
  10. 10.

    What is recursion in JavaScript?

    शुरुआती

    Recursion is a technique in which a function calls itself until it reaches a base case (a condition that stops further calls). Every recursive function must have a base case to avoid infinite loops and stack overflow errors.

    Example 01: Factorial

    function factorial(n) {
      if (n <= 1) return 1;        // base case
      return n * factorial(n - 1); // recursive call
    }
    
    console.log(factorial(5)); // 120 (5 × 4 × 3 × 2 × 1)
    console.log(factorial(0)); // 1

    Example 02: Fibonacci

    function fibonacci(n) {
      if (n <= 1) return n;
      return fibonacci(n - 1) + fibonacci(n - 2);
    }
    
    console.log(fibonacci(6)); // 8 (0, 1, 1, 2, 3, 5, 8)

    Example 03: Flatten a nested array

    function flattenArray(arr) {
      return arr.reduce((acc, val) =>
        Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val),
      []);
    }
    
    console.log(flattenArray([1, [2, [3, [4]], 5]])); // [1, 2, 3, 4, 5]

    Recursion vs Iteration:

    • Recursion is more readable for tree/graph traversal, nested structures, and divide-and-conquer problems
    • Iteration is more performant for simple loops — use it when recursion depth could be large

    Note: For deeply nested structures, iterative solutions with an explicit stack are preferred over recursion to avoid stack-overflow errors.

    ↥ back to top

  11. 11.

    What is the output of below spread operator array?

    शुरुआती
    [...'Hello']

    Output: ['H', 'e', 'l', 'l', 'o']

    Explanation: The string is an iterable type and the spread operator with in an array maps every character of an iterable to one element. Hence, each character of a string becomes an element within an Array.

    ↥ back to top

  12. 12.

    What is class expression in es6 class?

    शुरुआती

    A class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class\'s body. However, it can be accessed via the name property.

    Example:

    // Unnamed Class
    let Rectangle = class {
      constructor(height, width) {
        this.height = height;
        this.width = width;
      }
    };
    console.log(Rectangle.name); // Rectangle
    
    // Named Class
    let Triangle = class TriangleClass {
      constructor(base, height) {
        this.base = base;
        this.height = height;
      }
    };
    console.log(Triangle.name); // TriangleClass

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  13. 13.

    Name the two functions that are used to create an HTML element dynamically?

    शुरुआती

    In an HTML document, the document.createElement() method creates the HTML element specified by tagName.

    Syntax:

    const element = document.createElement(tagName[, options]);

    HTML

    <!DOCTYPE html>
    <html>
      <head>
          <title>||Working with elements||</title>
      </head>
    <body>
      <div id="app">The text above has been created dynamically.</div>
    </body>
    </html>

    JavaScript

    document.body.onload = addElement;
    
    function addElement () { 
      // create a new div element 
      var newDiv = document.createElement("div"); 
    
      var newContent = document.createTextNode("Hi there and greetings!"); 
      // add the text node to the newly created div
      newDiv.appendChild(newContent);  
    
      // add the newly created element and its content into the DOM 
      var currentDiv = document.getElementById("app"); 
      document.body.insertBefore(newDiv, currentDiv); 
    }

    Create Dynamic Button:

    // Create a button
    
    let btn = document.createElement("BUTTON");
    btn.innerHTML = "CLICK ME";
    document.body.appendChild(btn);

    Removing Elements Dynamically:

    // Removes an element from the document
    
    function removeElement(elementId) {    
      let element = document.getElementById(elementId);
      element.parentNode.removeChild(element);
    }

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  14. 14.

    What is generator in JS?

    शुरुआती

    Generator-Function:

    A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. The yield statement suspends function\'s execution and sends a value back to caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run.

    Syntax:

    function* gen() {
         yield 1;
         yield 2;
         yield 3;
         ...
    }

    Generator-Object:

    Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a "for in" loop.

    Example:

    // Generate Function
    
    function* fun() {
      yield 10;
      yield 20;
      yield 30;
    }
    
    // Calling the Generate Function
    var gen = fun(); // returns a Generator object (doesn\'t run yet)
    gen.next(); // { value: 10, done: false }
    gen.next(); // { value: 20, done: false }
    gen.next(); // { value: 30, done: false }
    gen.next(); // { value: undefined, done: true }

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  15. 15.

    What is event handling in javascript?

    शुरुआती

    The change in the state of an object is known as an Event. In html, there are various events which represents that some activity is performed by the user or by the browser.

    When javascript code is included in HTML, js react over these events and allow the execution. This process of reacting over the events is called Event Handling. Thus, js handles the HTML events via Event Handlers.

    Some of the HTML event handlers are:

    Mouse events:

    |Event Handler |Description

    onclickWhen mouse click on an element
    onmouseoverWhen the cursor of the mouse comes over the element
    onmouseoutWhen the cursor of the mouse leaves an element
    onmousedownWhen the mouse button is pressed over the element
    onmouseupWhen the mouse button is released over the element
    onmousemoveWhen the mouse movement takes place.

    Form events:

    Event HandlerDescription
    onfocusWhen the user focuses on an element
    onsubmitWhen the user submits the form
    onblurWhen the focus is away from a form element
    onchangeWhen the user modifies or changes the value of a form element

    Window/Document events:

    Event HandlerDescription
    onloadWhen the browser finishes the loading of the page
    onunloadWhen the visitor leaves the current webpage, the browser unloads it
    onresizeWhen the visitor resizes the window of the browser

    Example: Click Event

    <!DOCTYPE html>
    <html>
      <head>
        <script>
          function greeting() {
            alert("Hello! Good morning");
          }
        </script>
      </head>
      <body>
        <h2>Click Event Example</h2>
        <button type="button" onclick="greeting()">Click me</button>
      </body>
    </html>

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  16. 16.

    What is an Iterator?

    शुरुआती

    An iterator is an object which defines a sequence and a return value upon its termination. It implements the Iterator protocol with a .next() method which returns an object with two properties:

    • value: The next value in the iteration sequence.
    • done: This is true if the last value in the sequence has already been consumed.

    Example:

    // custom Iterator
    function numbers() {
      let n = 0;
      return {
        next: function () {
          n += 10;
          return { value: n, done: false };
        }
      };
    }
    
    // Create an Iterator
    const number = numbers();
    
    console.log(number.next()); // {value: 10, done: false}
    console.log(number.next()); // {value: 20, done: false}
    console.log(number.next()); // {value: 30, done: false}

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  17. 17.

    What is Babel and how does transpilation work?

    शुरुआती

    Babel is a JavaScript transpiler (source-to-source compiler) that converts modern JavaScript (ES6+) into a backwards-compatible version for older browsers or environments that don\'t support the latest syntax.

    How it works:

    1. Parse — Source code is parsed into an AST (Abstract Syntax Tree).
    2. Transform — Plugins traverse and modify the AST (e.g. convert arrow functions to regular functions).
    3. Generate — The modified AST is printed back to JavaScript source code.

    Installation:

    npm install --save-dev @babel/core @babel/cli @babel/preset-env

    `babel.config.json`:

    {
      "presets": [
        ["@babel/preset-env", {
          "targets": "> 0.25%, not dead",
          "useBuiltIns": "usage",
          "corejs": 3
        }]
      ],
      "plugins": ["@babel/plugin-transform-class-properties"]
    }

    Example transformation:

    // Input (ES6+)
    const greet = name => `Hello, ${name}!`;
    const [a, b, ...rest] = [1, 2, 3, 4];
    
    // Output (ES5)
    "use strict";
    var greet = function greet(name) {
      return "Hello, " + name + "!";
    };
    var _ref = [1, 2, 3, 4], a = _ref[0], b = _ref[1], rest = _ref.slice(2);

    Polyfills vs. transpilation:

    • Transpilation handles syntax (arrow functions, destructuring, classes).
    • Polyfills (core-js, regenerator-runtime) handle missing runtime APIs (Promise, Array.from, generators).

    ↥ back to top

  18. 18.

    What are static methods and properties, and how do they differ from instance members?

    शुरुआती

    The primary difference lies in where the data lives and what owns it:

    • Instance methods: Belong to individual objects created via new. Each object gets its own copy of the data.
    • Static methods: Belong to the class itself. There is only one copy shared across the entire application, and you do not need to create an object to use them.
    AccessMemoryInherited via
    Static method/propertyClassName.method()One copy on the classChildClass.__proto__
    Instance methodinstance.method()Shared on prototypeinstance.__proto__
    Instance propertyinstance.propOne copy per instanceOwn property

    Example:

    /**
     * Instance methods vs static methods
     */
    
    class Counter {
      static count = 0; // static — shared across all instances
    
      constructor(name) {
        this.name = name; // instance — unique per object
        Counter.count++;
      }
    
      static reset() {
        Counter.count = 0; // access via class name, not `this`
      }
    }
    
    const a = new Counter('a');
    const b = new Counter('b');
    
    console.log(Counter.count); // 2 — static, belongs to the class
    console.log(a.name);        // 'a' — instance, belongs to the object
    // console.log(a.count);    // undefined — statics aren't on instances
    
    Counter.reset();
    console.log(Counter.count); // 0

    ↥ back to top

  19. 19.

    What are the various statements in error handling?

    शुरुआती

    Below are the list of statements used in an error handling,

    1. try: This statement is used to test a block of code for errors
    2. catch: This statement is used to handle the error
    3. throw: This statement is used to create custom errors.
    4. finally: This statement is used to execute code after try and catch regardless of the result.

    Example:

    function errorHandling() {
    
      const message = document.getElementById("app");
      message.innerHTML = "";
      let x = document.getElementById("app").value;
      
      try {
        if (x === "") throw "is empty";
        if (isNaN(x)) throw "is not a number";
        x = Number(x);
        if (x > 10) throw "is too high";
        if (x < 5) throw "is too low";
      } catch (err) {
        message.innerHTML = "Error: " + err + ".";
      } finally {
        document.getElementById("app").value = "";
      }
    }
    
    errorHandling(); // Error: is not a number.

    &#9885; Try this example on CodeSandbox

    ↥ back to top

  20. 20.

    What is a conditional operator in javascript?

    शुरुआती

    The conditional (ternary) operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statement.

    Syntax:

    <condition> ? <value1> : <value2>;

    Example:

    const isAuthenticated = false;
    
    console.log(isAuthenticated ? 'Hello, welcome' : 'Sorry, you are not authenticated');

    ↥ back to top