Junior
How do the import and export operators work in JavaScript?
sobes.tech AI
Answer from AI
The import and export operators are used for working with modules in JavaScript, allowing code to be split into independent, reusable parts and managing dependencies between them.
export
The export operator is used to export variables, functions, classes, or other values from a module. Export can be named or a default export.
Named export:
// module.js
export const myVariable = 10;
export function myFunction() { // ... }
export class MyClass { // ... }
Default export: a module can have only one default export.
// module.js
const defaultValue = 'default value';
export default defaultValue;
import
The import operator is used to import values exported by other modules.
Named import:
// another-module.js
import { myVariable, myFunction } from './module.js';
Import with a different name:
// another-module.js
import { myVariable as newVariableName } from './module.js';
Import all named exports as an object:
// another-module.js
import * as moduleAlias from './module.js';
// Access: moduleAlias.myVariable, moduleAlias.myFunction
Import default export:
// another-module.js
import defaultValueName from './module.js';
Import both named and default exports simultaneously:
// another-module.js
import defaultValueName, { myVariable, myFunction } from './module.js';
Principles of operation:
- Static analysis: The JavaScript engine analyzes
importandexportoperators during compilation (before code execution), creating a dependency graph between modules. - "Live" bindings: Imported variables are not copies of values from the exporting module. They are "live" bindings (live references) to variables from the source module. If the value of a variable in the exporting module changes, this change will be visible through the imported binding.
- Single execution: The code of each module is executed only once upon the first import of that module. Export results are cached and used in subsequent imports.
- Context usage: Modules execute in their own context, isolated from the global scope. Variables declared at the root of a module do not pollute the global namespace unless they are explicitly exported.