CodeBlanks Logo Icon CodeBlanks

Project final - Library

JavaScript course · Advanced · Lesson 23/100

Finalize the library and import the module from another file to use it.

Importing a module

The library is complete: a Collection class, internal state and three methods, plus named and default exports. We can now use this module in another file.

To do that we use the import keyword. To take the default export we write import Collection from "./library.js"; the path is the module's relative location. Then we create an instance with new Collection() and call its methods.

Using an instance

After importing the module we create an instance with const list = new Collection(). We add items with chains like list.add("apple").add("pear") and search with list.find(item => item === "apple").

Here the item => ... form is an arrow function; find calls it for each item and returns the first one that yields true. This way we use the library in a real application.

Exercise Import the module and use it

The library.js module below is complete. In the app.js section, import the module with import, create a new Collection instance, add two items and find one with find.

Show example solution
Import with import Collection from "./library.js". Create an instance with new Collection(). Add items with add and find one with find.

Example solution:
import Collection from "./library.js";

const list = new Collection();
list.add("apple").add("pear");
const found = list.find(item => item === "apple");
console.log(found);

Test yourself

  1. What does import Collection from "./library.js" do?

    • It deletes the class
    • It imports the default export
    • It exports the class
    • It creates a new instance
    Show answer

    It imports the default export — Correct! import ... from imports the default export.

  2. Import the default export

    import Collection from "____";
    Show answer
    import Collection from "./library.js";
  3. Match the usage pieces

    import
    imports a module
    new Collection
    creates a new instance
    list.add
    adds an item
    list.find
    finds a matching item
  4. Write an arrow function for find

    const found = list.find(____);
    Show answer
    const found = list.find(item => item === "apple");

All lessons in Advanced