Top 10 JavaScript Interview Questions and Answers (2024) – Part 2

Here are the common Top 10 JavaScript Interview Questions asked during interview. Part1

1) How does the defer attribute impact the loading and execution of JavaScript files in a web page?

The objective of using the defer attribute in JavaScript is to optimize script loading by delaying execution until after HTML parsing, enhancing page load performance and maintaining execution order.

DOMContentLoaded Event: – Scripts with defer are executed right before the DOMContentLoaded event fires. This event indicates that the HTML document has been completely loaded and parsed, making it a suitable time for executing scripts that rely on the DOM being fully constructed.

Order Preservation: Scripts with the defer attribute are executed in the same sequence they appear in the HTML document. This ensures that if one script depends on another, they are executed in the correct order.

<!DOCTYPE html>
<html>
<head>
  <title>Order Preservation Example</title>
</head>
<body>
  <script src="script1.js" defer></script>
  <script src="script2.js" defer></script>
</body>
</html>

2) Can you explain the role of the <!DOCTYPE> declaration in web development? OR What happens if you omit the DOCTYPE declaration from an HTML document?

The objective of the <!DOCTYPE> declaration is to define the document type and version of HTML being used in a web page, ensuring consistent rendering across different browsers by triggering standards mode.

It ensures that browsers render the page in standards mode, interpreting HTML and CSS according to the specified version, thus promoting consistency and compatibility across various browsers and devices.

When we include the <!DOCTYPE html> declaration at the beginning of the document, as shown below, the browser knows to render the page in standards mode according to HTML5 specifications:

<!DOCTYPE html>
<html>
<head>
  <title>Example Page</title>
</head>
<body>
  <h1>Hello, World!</h1>
</body>
</html>
<!-- Without DOCTYPE declaration -->
<html>
<head>
  <title>Page Without DOCTYPE</title>
</head>
<body>
  <h1>Hello, World!</h1>
</body>
</html>

In this example, without the <!DOCTYPE> declaration, the browser may default to quirks mode, resulting in unpredictable rendering behavior.

Quirks mode: – the browser may render the webpage with various non-standard behaviors and rendering quirks, often leading to inconsistencies in layout and styling across different browsers.

Some common characteristics of quirks mode include:

  1. Box Model Differences: In quirks mode, the CSS box model may behave differently compared to standards mode, leading to unexpected spacing and layout issues.
  2. Default Margins and Padding: Browsers may apply default margins and padding to certain elements in quirks mode, which can affect the overall layout of the webpage.
  3. CSS Parsing Differences: CSS rules may be interpreted differently in quirks mode, leading to inconsistencies in styling and presentation.
  4. JavaScript Compatibility: Some JavaScript behaviors may differ in quirks mode, potentially causing compatibility issues with scripts written for standards-compliant browsers.

3) Can you explain the purpose of the async attribute in JavaScript when used with <script> tags?

<script src="script.js" async></script>

It tells the browser to download the script.js file asynchronously while continuing to parse the HTML document. The script is then executed as soon as it’s downloaded, even if other parts of the page are still loading or parsing.

For example, consider a webpage with the following script tags:

<!DOCTYPE html>
<html>
<head>
  <title>Async Attribute Example</title>
</head>
<body>
  <script src="script1.js" async></script>
  <script src="script2.js" async></script>
</body>
</html>

In this example, both script1.js and script2.js will be downloaded asynchronously. They will be executed as soon as they are downloaded, without waiting for other resources to finish loading. This can improve page load times, especially for non-essential scripts that don’t require synchronous execution.

However, it’s important to note that scripts with the async attribute may not necessarily execute in the order they appear in the HTML document. If the order of execution is critical, you should consider using the defer attribute instead.

4) When would you use the async attribute compared to the defer attribute in script tags?

You would use the async attribute in script tags when you have non-blocking scripts that can be executed independently and do not rely on the DOM being fully constructed.

AttributeUse CaseExecution OrderDOM DependencyParsing Delay
asyncUse for non-blocking scripts that can be executed independently.May execute out of order as soon as script is available.Not guaranteed. Script may execute before or after DOMContentLoaded event.No delay in parsing. Script is executed asynchronously while HTML parsing continues.
deferUse for scripts that depend on the DOM being fully constructed or need to execute in a specific order.Executes in order right before DOMContentLoaded event.Scripts are executed after DOMContentLoaded event.No delay in parsing. Script is executed asynchronously while HTML parsing continues.

5) How would you create and utilize custom elements in HTML?

<script>
  customElements.define('my-custom-element', class extends HTMLElement {
    constructor() {
      super(); 
      this.innerHTML = 'This is my custom element!';
    }
  });
</script>
<my-custom-element></my-custom-element>

Custom elements are created using the HTML Custom Elements API, which allows developers to define their own reusable HTML tags.

Start by defining a custom element using the customElements.define() method. This method takes two parameters: the name of the custom element and the class that defines its behavior.

In JavaScript, when you define a custom element by extending the HTMLElement class (or any other built-in DOM element class), you are essentially creating a new class that inherits from HTMLElement. This inheritance allows your custom element to inherit properties and methods from its parent class, in this case, HTMLElement.

The super() call within the constructor of your custom element class is used to explicitly call the constructor of the parent class (HTMLElement). This ensures that any necessary initialization performed by the parent class’s constructor is also executed for your custom element.

class MyAutonomousElement extends HTMLElement {
  constructor() {
    super(); 
    this.innerHTML = 'This is my autonomous custom element!';
  }
}
customElements.define('my-autonomous-element', MyAutonomousElement);
<my-autonomous-element></my-autonomous-element>

There is another way to create custom elements in HTML documents, known as Autonomous Custom Elements. Autonomous custom elements are registered using the customElements.define() method just like customized built-in elements, but they are not based on existing HTML elements like HTMLElement. Instead, they are standalone elements with no inherent behavior.

Autonomous custom elements are useful when you want to create completely custom elements with no reliance on existing HTML elements. They provide a way to encapsulate functionality and styling within a custom element, making your HTML markup cleaner and more modular.

Leave a Comment