It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 72 - Named Exports in JavaScript Modules

JavaScript Modules allow us to break our code into separate files, making it more maintainable and organized. One way to share functions, variables, or classes between files is by using named exports.


What Are Named Exports?

Named exports allow you to export multiple values from a file. Each value must be referenced by its exact name when imported.


Syntax: Exporting

You can export as you declare, or export later in a list.

Example 1: Export As You Declare

// mathUtils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

Example 2: Export later

// mathUtils.js
const multiply = (a, b) => a * b;
const divide = (a, b) => a / b;

export { multiply, divide };

Syntax: Importing Named Exports

To import named exports, you use curly braces {} and the exact exported names.

// main.js
import { add, subtract } from './mathUtils.js';

console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2

If you only need one or two of the exported members, you can import just those:

import { multiply } from './mathUtils.js';

Renaming While Importing

You can rename a named export during import using **as**:

import { add as addition } from './mathUtils.js';

console.log(addition(2, 3)); // 5

Key Points

  • Named exports let you export multiple bindings (functions, variables, objects) by name.
  • You can mix export styles in the same file.
  • When importing, the names must match unless you rename them using as.

Try Your Hand

  1. Create a file helpers.js with two functions: capitalize and lowercase. Export both.
  2. In app.js, import and use both functions.
  3. Try renaming capitalize to makeUpper when importing.