WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Advanced · question 48 of 100

What are the different ways to handle module loading in JavaScript, such as CommonJS, AMD, and ES6 Modules?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

In JavaScript, there are several different ways to handle module loading. Here are some of the most common approaches:

CommonJS: CommonJS is a module system used by Node.js that allows you to define modules with module.exports and require. Here’s an example:

    // Define a module
    module.exports = {
        add: function(a, b) {
            return a + b;
        }
    };
    
    // Use the module in another file
    const math = require('./math');
    const result = math.add(2, 3); // result = 5

AMD (Asynchronous Module Definition): AMD is a module system used in browser environments that allows you to define modules with define and load them asynchronously with a module loader like RequireJS. Here’s an example:

    // Define a module
    define('math', [], function() {
        return {
            add: function(a, b) {
                return a + b;
            }
        };
    });
    
    // Use the module in another file
    require(['math'], function(math) {
        const result = math.add(2, 3); // result = 5
    });
    
    ES6 Modules: ES6 modules are a native module system that's built into modern browsers and Node.js. They allow you to define modules with export and import. Here's an example:
    javascript
    Copy code
    // Define a module
    export function add(a, b) {
        return a + b;
    }
    
    // Use the module in another file
    import { add } from './math';
    const result = add(2, 3); // result = 5

ES6 modules are the most modern and widely supported module system in JavaScript today, and they offer several advantages over other systems, including improved performance and better support for static analysis and tooling.

Each of these module systems has its own strengths and weaknesses, and the best choice depends on your specific use case and development environment. However, with the increasing adoption of ES6 modules, it’s likely to become the de facto standard for module loading in JavaScript in the near future.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics