DEV Community

Hiral
Hiral

Posted on

Javascript Modules

Modern JavaScript development depends on modules in which code is split into smaller, reusable and maintainable code.

First try to understand the problem,if you have single file
//app.js
function add(a,b) return a +b
function multiply(a,b)return a*b

Now as code grows

  • Files becomes too large
  • Code becomes hard to read
  • Duplication arise
  • Resuing the code is painful This where modules comes into picture:

What is Module
A module is simply a file that contains code(function, variables, classes)that you export and reuse into another files.

Exporting function or variables

export const PI = 3.14
export function add(a,b){
return a+b
}
Enter fullscreen mode Exit fullscreen mode

You can export multiple things from a module

Importing Modules

To use export Modules,you import it
// app.js

import { add, PI } from './math.js'; 
console.log(add(2, 3)); // 
5 console.log(PI); // 3.14
Enter fullscreen mode Exit fullscreen mode

You must use exact name when importing modules.

Default vs Named Exports

Default Export:
A module can have one default export
// greet.js

export default function greet(name) {
  return `Hello, ${name}`;
}
Enter fullscreen mode Exit fullscreen mode

Import it like this:

import greet from './greet.js';

console.log(greet('Alice'))

**Named Export**
// utils.js
`export const square = x => x * x;
export const cube = x => x * x * x;
Enter fullscreen mode Exit fullscreen mode

Import:

import { square, cube } from './utils.js';`
Enter fullscreen mode Exit fullscreen mode

In Short:

  • Modules help to organize code
  • Modules prevent naming conflicts
  • Modules helps in better readability
  • Modules can be reused in entire application

Top comments (0)