Importing with import
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 9 of 56.
After exporting functionality from a module, we need to import it to use it in another file. The import statement allows us to bring in exported values from other modules.
Import a named export:
// Importing a specific function from a module
import { greet } from './greeting.js';
// Now we can use the greet function
greet('John'); // Outputs: Hello, John!You can import multiple named exports at once:
// Importing multiple exports
import { greet, farewell } from './greeting.js';
greet('John'); // Outputs: Hello, John!
farewell('John'); // Outputs: Goodbye, John!Import a default export:
// Importing a default export (no curly braces needed)
// Use this when the other file has: export default functionName
import Person from './person.js';
// Create a new Person
const john = new Person('John');Challenge
EasyYou're building a signup form. You have a file validation-utils.js that contains useful email validation functions.
Your task:
- Import the
validateEmailfunction inmain.js(It is the named export, not the default export) - Call the function and pass the user@example.com email address
- Print the results using
console.log
Cheat sheet
Use the import statement to bring in exported values from other modules.
Import a named export:
import { greet } from './greeting.js';
greet('John'); // Outputs: Hello, John!Import multiple named exports:
import { greet, farewell } from './greeting.js';
greet('John'); // Outputs: Hello, John!
farewell('John'); // Outputs: Goodbye, John!Import a default export (no curly braces needed):
import Person from './person.js';
const john = new Person('John');Try it yourself
// TODO: Import the validateEmail function here (it is the named export)
// TODO: Call the function and pass user@example.com email address and print the results 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