Course contentsShow
← JavaScript
Lesson 1400 of 2,72331. ModulesFree lesson

Exporting at Declaration

Learn to export functions, classes, and variables directly at their declaration.

Exporting at Declaration

You'll learn how to combine the export keyword with your function, class, or variable declarations for cleaner, more direct module exports.

When creating modules, you can export items in two ways: declare them first and export them later, or export them right as you declare them. The second approach—exporting at declaration—keeps related code together and makes your exports immediately visible.

The Direct Approach

Instead of writing a function and then exporting it separately:

// Later export style
function greet(name) {
  return `Hello, ${name}!`;
}

export { greet };

You can export directly at declaration:

// Export at declaration
export function greet(name) {
  return `Hello, ${name}!`;
}

The export keyword simply goes right in front of your declaration. This works with functions, classes, variables—any named export you're creating.

Why This Matters

Exporting at declaration creates a single source of truth. When you see export at the start of a line, you immediately know that item is part of the module's public API. There's no need to scroll to the bottom of the file to check what's exported.

export const API_KEY = 'abc123';
export class User { /* ... */ }
export function validateEmail(email) { /* ... */ }

Each item clearly announces its exported status right where it's defined. This pattern is particularly useful in modules with many exports, where a long export list at the end can become unwieldy.

Key Takeaway: Export at declaration by placing the export keyword directly before function, class, const, let, or var declarations—it's clearer and keeps your module's public interface obvious at a glance.