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 73 - Mixing Named and Default Exports in JavaScript

JavaScript modules allow you to use both named and default exports in the same file. This gives you the flexibility to expose one primary functionality (default export) and additional utilities (named exports) from the same module.


Recap: Export Types

  • Default export ? The main export from a file (no curly braces needed on import).
  • Named exports ? You can have multiple named exports (imported with curly braces).

Mixing Both: Example

// utils.js

export default function greet(name) {
  return `Hello, ${name}!`;
}

export function add(a, b) {
  return a + b;
}

export const PI = 3.14159;

Importing Both Together

You can import the default and named exports at the same time:

// main.js

import greet, { add, PI } from './utils.js';

console.log(greet("Lance")); // Hello, Lance!
console.log(add(2, 3));      // 5
console.log(PI);             // 3.14159

Notes

  • The default export can be renamed to anything you like.
  • Named exports must be imported using the exact names (or renamed using as).
  • You can skip importing the default or named exports if you don’t need them.

Common Mistakes

//  Wrong: Trying to import default as named
import { greet } from './utils.js'; // Error if greet is default

//  Correct
import greet from './utils.js';

Try Your Hand

  1. Create a mathUtils.js file:

    • Default export a calculateArea(radius) function.
    • Named export constants: PI = 3.14, E = 2.718.
  2. Import everything in a main.js file and use them to compute and log results.


Self - Quiz

  1. Can you have both named and default exports in the same file?
  2. Do you need curly braces to import the default export?
  3. What’s the benefit of mixing export types in one module?