Menu
Coddy logo textTech

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 icon

Challenge

Easy

You're building a signup form. You have a file validation-utils.js that contains useful email validation functions.

Your task:

  1. Import the validateEmail function in main.js (It is the named export, not the default export)
  2. Call the function and pass the user@example.com email address
  3. 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.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