Menu
CoddyTech

Default Exports

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 8 of 33.

This lesson adds store.js, a file about one thing: the store that holds your notes. A file like that shares its one thing as its default export, and the file that imports it picks any name for it.

export default marks the one value a file is about. The importer gives it any name and writes no braces:

// config.js
const config = { port: 3000 };
export default config;

// app.js
import settings from './config.js';
console.log(settings.port);

Braces ask for a named export, so import { config } from './config.js' fails here: config.js names nothing. Use a default export for a file's main value and named exports for a file of helpers.

challenge icon

Challenge

Easy

Your notes need one place to live. The new file store.js holds them in a store object, which starts with three notes in store.notes. Share that store with notes.js, and use it in add and list.

  1. In store.js, make store the file's default export. The comment at the bottom marks the spot.
  2. In notes.js, import the store at the top, next to the formatNote import. A default import has no curly braces.
  3. In the add branch, add the note with store.add(text). It returns the new note's number. Print Adding: followed by the note, formatted with that number. The store starts with three notes, so node notes.js add Buy bread prints:
    Adding: 4. Buy bread
  4. In the list branch, keep the Notes for ... heading. Under it, replace No notes yet with every note in the store, one per line, each formatted with formatNote and numbered from 1. node notes.js list prints:
    Notes for you
    1. Buy milk
    2. Call Ada
    3. Water the plants
    If the store has no notes, still print No notes yet under the heading.

Try it: type add Buy bread in the box after $ node notes.js and press Enter. You see Adding: 4. Buy bread. Then type list: you see the three starting notes, but not Buy bread. The store lives in memory, so every run starts again from the three notes in store.js. Chapter 3 saves notes to a file.

Try it yourself

// The notes live here until chapter 3 saves them to a file.
const store = {
    notes: ['Buy milk', 'Call Ada', 'Water the plants'],
    add(text) {
        this.notes.push(text);
        return this.notes.length;
    },
};

// Make store the default export of this file.

All lessons in Node.js Basics

Practice on your own: Express playground