JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What are JavaScript modules and how do I use them?

Asked on Jul 14, 2024

Answer

JavaScript modules allow you to break down your code into separate files, making it easier to manage and reuse. They help in organizing code by exporting and importing functionalities between different files.
<!-- BEGIN COPY / PASTE -->
        // file: mathUtils.js
        export function add(a, b) {
            return a + b;
        }

        export function subtract(a, b) {
            return a - b;
        }

        // file: main.js
        import { add, subtract } from './mathUtils.js';

        console.log(add(5, 3)); // Outputs: 8
        console.log(subtract(5, 3)); // Outputs: 2
        <!-- END COPY / PASTE -->
Additional Comment:
  • JavaScript modules use "export" to make functions, objects, or values available for import in other files.
  • Use "import" to bring in the exported functionalities from another module.
  • Ensure your environment supports ES6 modules, or use a tool like Babel to transpile your code.
  • Remember to use the ".js" extension when importing modules in a browser environment.
✅ Answered with JavaScript best practices.
← Back to All Questions