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
EasyYou have two files <strong>main.js</strong> and <strong>weather-utils.js</strong>. Your task:
- In
<strong>weather-utils.js</strong>: Add theexportkeyword to make thegetWeatherMessagefunction available to other files - In
<strong>main.js</strong>: Call the importedgetWeatherMessagefunction with temperature 15 and print the result usingconsole.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.logThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge