JavaScript Interview Questions
JavaScript
Web DevelopmentFrontendBackendQuestion 3
What are modules in JavaScript?
Answer:
Modules in JavaScript are reusable pieces of code that can be exported from one program and imported for use in another. They help in organizing and managing code by encapsulating functionality, reducing dependencies, and enhancing maintainability. ES6 introduced native support for modules, which can be imported and exported using the import
and export
keywords.
Here is an example demonstrating the use of modules:
// module.js
export function greet(name) {
return `Hello, ${name}`;
}
export const pi = 3.14;
// main.js
import { greet, pi } from './module.js';
console.log(greet('John')); // 'Hello, John'
console.log(pi); // 3.14
In this example, greet
and pi
are exported from module.js
and imported into main.js
, demonstrating how to use modules to organize code and share functionality between different parts of an application.