JavaScript
/Intermediate
JS Modules
Definition
Modules are small, independent, reusable pieces of code. JavaScript supports ES6 Modules natively, allowing you to `export` variables, functions, or classes from one file and `import` them into another.
Explain Like I'm New
Imagine you are building a Lego castle. Instead of having all 5,000 pieces in one massive pile (a single huge JS file), you put the roof pieces in one bag, the wall pieces in another, and the knights in another. When you need knights, you just `import` the knight bag. It keeps your code organized and prevents pieces from getting mixed up.
Real World Example
In React, every component (like a Button or a Navbar) is usually written in its own file (Module). Then, the main App file imports them. This makes the code readable and easy to collaborate on.
Common Use Cases
- •Splitting large codebases into manageable files
- •Encapsulating private logic (variables not exported stay private to the file)
- •Reusing utility functions across multiple projects
Interactive Example
// --- mathUtils.js (The Module) --- // Named exports export const PI = 3.14159; export function add(a, b) { return a + b; } // Default export (only one per file) export default class Calculator { multiply(a, b) { return a * b; } } // --- main.js (The Consumer) --- // Importing a default export (no braces, name it whatever) import MyCalc from './mathUtils.js'; // Importing named exports (must use braces and exact name) import { PI, add } from './mathUtils.js'; // You can also rename named exports on import import { add as sum } from './mathUtils.js'; const calc = new MyCalc(); console.log(calc.multiply(2, 5)); // 10 console.log(PI); // 3.14159 console.log(sum(5, 5)); // 10
Interview Questions
basic
- What is the difference between default export and named export?
- How do you import a default export?
intermediate
- Can a module have both named exports and a default export?
- What happens if you try to modify an imported variable?
advanced
- What is the difference between ES Modules (ESM) and CommonJS (CJS)?
- How does dynamic import() work and why is it useful?
trick
- Does importing the same module twice execute the module code twice?