Why do developers use modules in JavaScript?
Think about how breaking code into parts helps manage big projects.
Modules help organize code into smaller, reusable parts and avoid naming conflicts by keeping variables and functions private to each module.
What will be the output of this JavaScript code using modules?
export const greeting = 'Hello'; import { greeting } from './module.js'; console.log(greeting);
Imported variables keep their exported values.
The variable greeting is exported and then imported correctly, so logging it prints 'Hello'.
Consider this code:
import { value } from './mod.js';
import { value as val2 } from './mod.js';
console.log(value, val2);What is the output?
Modules are cached and importing multiple times returns the same values.
Importing the same module multiple times does not reload it. Both imports get the same exported value, so both variables hold 42.
How do JavaScript modules help prevent global scope pollution?
Think about where variables live when you use modules.
Modules create their own scope, so variables and functions declared inside do not appear in the global scope, avoiding conflicts.
Given two modules:
// a.js
import { bValue } from './b.js';
export const aValue = 'A';
console.log('a.js:', bValue);
// b.js
import { aValue } from './a.js';
export const bValue = 'B';
console.log('b.js:', aValue);What will be printed when a.js is run?
Think about how JavaScript handles circular imports and initialization order.
When b.js imports aValue from a.js, aValue is not yet initialized, so it is undefined. Then bValue is exported as 'B'. When a.js logs bValue, it is 'B'.