JavaScript Interview Questions and Answers (2024)

author image Hirely
at 05 Jan, 2025

Question: What are closures in JavaScript?

Answer:

In JavaScript, a closure is a function that remembers and retains access to its lexical scope (the environment in which it was created), even when the function is executed outside that scope.A closure allows a function to access variables from its outer enclosing function even after the outer function has finished execution.

Key Points About Closures:

  1. Function Inside a Function : A closure occurs when a function is defined inside another function and the inner function refers to variables of the outer function.

  2. Lexical Scope : The inner function remembers the scope in which it was created, including all the variables in the outer function’s scope, even after the outer function has finished executing.

  3. Persistent State : Closures enable the inner function to persist the state of the outer function’s variables, allowing those variables to be used even after the outer function returns.

Example of a Closure:

function outer() {
  let outerVariable = 'I am from outer function'; // outer function's variable

  function inner() {
    console.log(outerVariable); // inner function has access to outerVariable
  }

  return inner; // Returning the inner function as a closure
}

const closureFunction = outer(); // outer() runs, but inner() retains access to outerVariable
closureFunction(); // Output: I am from outer function

How It Works:

  • outer() is executed, and it defines a local variable outerVariable and a function inner().

  • When outer() is invoked, it returns the inner() function.

  • Even though the execution of outer() is complete, the inner() function still has access to outerVariable, creating a closure.

Closures and Private Variables:

Closures can be used to create private variables in JavaScript, which can’t be accessed directly from outside the function but can be modified or accessed via closures.

Example:

function counter() {
  let count = 0; // This variable is private to the counter function

  return {
    increment: function() {
      count++;
      console.log(count);
    },
    decrement: function() {
      count--;
      console.log(count);
    },
    getCount: function() {
      return count;
    }
  };
}

const myCounter = counter();
myCounter.increment(); // Output: 1
myCounter.increment(); // Output: 2
console.log(myCounter.getCount()); // Output: 2
myCounter.decrement(); // Output: 1
  • In the above example, count is private and can only be accessed or modified through the increment(), decrement(), and getCount() methods, which are closures.

Benefits of Closures:

  1. Encapsulation : Closures allow for data encapsulation, hiding implementation details and providing controlled access to variables.

  2. Data Persistence : They allow functions to maintain state between calls.

  3. Partial Application : Closures can be used to create functions with preset parameters, which is useful in scenarios like event handling or configuration.

Summary:

  • A closure is a function that retains access to its lexical scope even after the outer function has finished execution.

  • Closures are important for creating private variables , maintaining state, and data encapsulation in JavaScript.

Question: What is the DOM (Document Object Model)?

Answer:

The DOM (Document Object Model) is a programming interface for web documents. It represents the structure of an HTML or XML document as a tree of objects and allows programming languages (like JavaScript) to interact with and manipulate the content, structure, and styles of web pages dynamically.

Key Concepts of the DOM:

  1. Document as an Object : The DOM treats the entire HTML or XML document as an object, where each part of the document (elements, attributes, text) is represented as a node. The document is structured as a tree, known as the DOM tree , with the root node representing the entire document.

  2. Tree Structure : The DOM represents the document as a hierarchical tree structure, where each node is an object representing a part of the page (e.g., an element, text, attribute, etc.).

  • Root Node : The root of the tree is the document object.

  • Element Nodes : These represent HTML elements, such as <div>, <p>, <a>.

  • Text Nodes : These contain the text content within an element.

  • Attribute Nodes : These represent the attributes of elements, such as class, id, or src.

Example of a DOM tree for the HTML:

<html>
  <body>
    <div id="container">
      <p>Hello, World!</p>
    </div>
  </body>
</html>
  • The DOM structure for this HTML would look something like this:
document
  └── html
      └── body
          └── div (id="container")
              └── p (text: "Hello, World!")
  1. Access and Manipulation : The DOM provides methods and properties to access , modify , add , or remove elements and their content dynamically. This allows JavaScript to change the structure, style, and behavior of web pages in response to user interaction or other events. Examples:
  • Accessing Elements :
const element = document.getElementById('container'); // Accessing an element by its ID
const paragraphs = document.getElementsByTagName('p'); // Accessing all <p> elements
  • Modifying Content :
element.innerHTML = 'New Content'; // Change the content of an element
paragraphs[0].textContent = 'Updated Text'; // Modify text content of the first <p> element
  1. Events and Interaction : The DOM allows for handling events (like clicks, key presses, form submissions, etc.) that users trigger on the page. JavaScript can be used to respond to these events and modify the page accordingly. Example:
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
  alert('Button clicked!');
});
  1. Dynamic Updates : The DOM is dynamic , meaning changes made to it are reflected immediately on the webpage. When JavaScript modifies the DOM, the page is updated in real-time without needing a full reload. This is what enables interactive and dynamic web pages.

  2. Browser Representation : Web browsers (like Chrome, Firefox, or Safari) create a DOM from the HTML document, and it is this DOM that is manipulated through JavaScript to update the content displayed in the browser.

Key Methods and Properties of the DOM:

  • Accessing Elements :
    • document.getElementById(id): Finds an element by its ID.

    • document.getElementsByClassName(className): Finds elements by their class name.

    • document.getElementsByTagName(tagName): Finds elements by their tag name.

    • document.querySelector(selector): Finds the first element that matches a CSS selector.

    • document.querySelectorAll(selector): Finds all elements that match a CSS selector.

  • Manipulating Elements :
    • element.innerHTML: Gets or sets the HTML content of an element.

    • element.textContent: Gets or sets the text content of an element.

    • element.setAttribute(attribute, value): Sets an attribute on an element.

    • element.appendChild(child): Appends a new child element to the element.

  • Events :
    • element.addEventListener(event, callback): Attaches an event listener to an element.

Example of DOM Manipulation:

<!DOCTYPE html>
<html>
<head>
  <title>DOM Example</title>
</head>
<body>
  <button id="myButton">Click Me!</button>
  <p id="message">Hello, World!</p>

  <script>
    // Access the button and paragraph elements
    const button = document.getElementById('myButton');
    const message = document.getElementById('message');

    // Add a click event listener to the button
    button.addEventListener('click', function() {
      message.textContent = 'You clicked the button!';
    });
  </script>
</body>
</html>

In this example:

  • When the button is clicked, the text content of the paragraph changes from "Hello, World!" to "You clicked the button!".

Summary:

  • The DOM (Document Object Model) is an interface that allows JavaScript to interact with the HTML or XML structure of a webpage.

  • It represents the document as a tree of objects, where each element, attribute, and piece of text is a node.

  • JavaScript can access, manipulate, and update these nodes dynamically to create interactive and dynamic web applications.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as JavaScript interview questions, JavaScript interview experiences, and details about various JavaScript job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now