Menu
Coddy logo textTech

Exporting with export

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

When organizing your JavaScript code across multiple files, the export keyword allows you to expose functions, variables, and other code so they can be used in other files.

Let's create two simple functions that we want to export:

File: math-utils.js
// A function that adds two numbers
function add(a, b) {
    return a + b;
}
// A function that multiplies two numbers  
function multiply(a, b) {
    return a * b;
}
// Export the functions so other files can use them
export { add, multiply };

Alternatively, you can use the inline export syntax:

File: math-utils.js
// Export functions directly
export function add(a, b) {
    return a + b;
}
export function multiply(a, b) {   
return a * b;
}
challenge icon

Challenge

Easy

You have two files <strong>main.js</strong> and <strong>weather-utils.js</strong>. Your task:

  1. In <strong>weather-utils.js</strong>: Add the export keyword to make the getWeatherMessage function available to other files
  2. In <strong>main.js</strong>: Call the imported getWeatherMessage function with temperature 15 and print the result using console.log

Cheat sheet

The export keyword allows you to expose functions, variables, and other code from one file so they can be used in other files.

You can export functions using the export statement at the end of the file:

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

function multiply(a, b) {
    return a * b;
}

export { add, multiply };

Alternatively, you can use inline export syntax:

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

export function multiply(a, b) {
    return a * b;
}

Try it yourself

import { getWeatherMessage } from './weather-utils.js';

// TODO: Call getWeatherMessage function with temperature 15 and print the result using console.log
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