Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js Modules in JavaScript

Js Modules in JavaScript

? JavaScript Modules

JavaScript modules help you organize code by splitting it into reusable pieces. Each module can export variables, functions, or classes and import from others.


Why use Modules?

  • Encapsulation: Keep code organized and avoid polluting the global scope.

  • Reusability: Use the same code in different files.

  • Maintainability: Easier to manage large projects.

  • Native support in modern JavaScript (ES6+).


? Exporting and Importing

1. Named Exports

You explicitly export multiple values by name:

// math.jsexport const pi = 3.14159;export function square(x) {  return x * x;}

Import them by the same name:

// app.jsimport { pi, square } from './math.js';console.log(pi);        // 3.14159console.log(square(4)); // 16

2. Default Exports

Each module can have one default export, useful for a main function or class:

// logger.jsexport default function log(message) {  console.log(message);}

Import without curly braces:

// app.jsimport log from './logger.js';log('Hello Modules!');

3. Renaming Imports/Exports

// math.jsexport { square as sq };// app.jsimport { sq as square } from './math.js';

? Module File Requirements

  • Use .js extension (or .mjs for Node.js).

  • In browsers, add <script type="module" src="app.js"></script>.

  • Modules are always in strict mode.

  • Imports are deferred, running after HTML parsing.


? Dynamic Imports

Import modules dynamically (returns a promise):

button.addEventListener('click', async () => {  const module = await import('./math.js');  console.log(module.pi);});

Summary

FeatureDescription
exportExport variables, functions, classes
importImport them into another file
Named exportsExport multiple named values
Default exportExport a single main value
Dynamic importsLoad modules on demand (async)

Want a demo project setup or how to use modules in Node.js?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql