Menu
Coddy logo textTech

Default vs. Named Exports

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 10 of 56.

In JavaScript modules, you have two main ways to export your code: named exports and default exports.

Named Exports allow you to export multiple values from a module:

// math.js
export function add(a, b) {
    return a + b;
}
export function subtract(a, b) {
    return a - b;
}

When importing named exports, you must use the exact same names within curly braces:

// app.js
import { add, subtract } from './math.js';

console.log(add(5, 3));      // 8
console.log(subtract(10, 4)); // 6

If you need to rename a named import, use the as keyword to create an alias:

// app.js
import { add as sum, subtract as minus } from './math.js';

console.log(sum(5, 3));   // 8
console.log(minus(10, 4)); // 6

Default Exports allow you to export a single main value from a module:

// user.js
const user = {
  name: 'John',
  age: 30
};

export default user;

When importing a default export, you can use any name you want without curly braces:

// app.js
import person from './user.js';

console.log(person.name); // 'John'

When to use which? Use named exports when a module provides multiple related utilities (e.g., a collection of helper functions). Use a default export when a module has one primary purpose or main value (e.g., a class, a component, or a configuration object).

You can combine both types of exports in a single module:

// vehicle.js
export const wheels = 4;
export const doors = 4;

const car = {
  brand: 'Toyota',
  model: 'Corolla'
};

export default car;

And import them together:

// app.js
import myCar, { wheels, doors } from './vehicle.js';

console.log(myCar.brand);  // 'Toyota'
console.log(wheels);       // 4
challenge icon

Challenge

Easy

You have two files. Your task is to set up the exports in calculator.js and imports in main.js.

  1. In calculator.js: Export calculate as default and square as named
  2. In main.js: Import both functions correctly

Tests will check:

  • Default export used for calculate
  • Named export used for square
  • Both imports work correctly

Try it yourself

// TODO: Import both functions here from calculator.js


// Test
console.log(calculate(10, 5, '+')); // Should output 15
console.log(square(4));             // Should output 16
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming