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

JavaScript · Intermediate · question 33 of 100

What are JavaScript modules, and how do you import and export them?

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

JavaScript modules are a way to organize and structure code into reusable and independent units. Modules can contain functions, classes, or any other JavaScript code, and they can be imported and exported to other modules to share functionality between them.

Modules are defined in separate files, each with its own scope, and they are loaded asynchronously by the browser or the Node.js environment. Modules can also be loaded using the import and export statements, which are part of the ECMAScript 6 (ES6) module syntax.

Here’s an example of how to export a function from a module:

    // myModule.js
    export function sayHello() {
        console.log("Hello, world!");
    }

In this example, the sayHello() function is exported from the myModule.js module using the export keyword. This makes the function available for import by other modules.

Here’s an example of how to import the sayHello() function into another module:

    // main.js
    import { sayHello } from './myModule.js';
    
    sayHello();

In this example, the sayHello() function is imported into the main.js module using the import statement, and it is called to log "Hello, world!" to the console.

You can also use the export keyword to export variables, classes, or default exports:

    // myModule.js
    export const myVar = "Hello";
    export class MyClass { /* ... */ }
    export default function() { /* ... */ }
    // main.js
    import myFunc from './myModule.js';
    import { myVar, MyClass } from './myModule.js';

In this example, myVar and MyClass are imported using the object destructuring syntax, while myFunc is imported as the default export using the import ... from syntax.

JavaScript modules provide a powerful and flexible way to organize and share code between modules, and they are widely used in modern web development. However, the exact syntax and behavior of modules can vary depending on the environment and tools being used, so it’s important to check the documentation and best practices for your specific use case.

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