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
Loading Code Playground...
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?