# Question 37

### Question

Can you explain how to use dynamic imports with `import()` function in ES6 modules with 1 practical use case?

### Answer

**Basic Syntax:**

```javascript
const modulePromise = import('./myModule.js'); // Imports 'myModule.js' asynchronously

modulePromise.then(
    // Resolve: Module loaded successfully
    ({ default, ... }) => {
        console.log("Module imported:", default); 
        // Use the imported functions/variables
        default.doSomething();  
    },
    // Reject: Error loading module
    error => {
        console.error("Error importing module:", error);
    }
);
```

**Practical Use Case: On-Demand Loading of Features**

Imagine building a web application with different features (e.g., a chat, image editor, analytics dashboard). You don't want to load all these features at once, as it might slow down the initial page load. Dynamic imports let you load them only when needed.

```javascript
// index.js (main app file)
console.log("App loading...");

const chatModuleButton = document.getElementById('chat-module-button');

chatModuleButton.addEventListener('click', async () => {
    try {
        const chatModule = await import('./modules/chat'); // Import only when clicked
        chatModule.init(); // Initialize the chat module 
    } catch (error) {
        console.error("Error loading chat module:", error);
    }
});

// ./modules/chat.js (Chat module code)
export function init() {
    console.log("Chat module loaded!");
    // ... Chat functionality implementation 
}
```

**Explanation:**

* The `chatModuleButton` triggers the dynamic import of `./modules/chat`.
* The `await` keyword pauses execution until the import is complete.
* Once imported, `chatModule.init()` initializes the chat module's functionality.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://choubey.gitbook.io/javascript-interview-questions/question-37.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
