Importing Defaults and Built-In Modules

Your digest.js now imports isBlank, parseLine, and summarise from readings.js in one pair of braces. The school’s dashboard developers have already written the next piece Dev needs, a format.js that turns a reading into a report line. Halden Heating’s report should match the dashboard.

Their file shares its function in a way Python has no word for, a default export, and much of the JavaScript you’ll read uses one. In this lesson, you’ll import a default, decide when your own files should have one, and import the modules built into Node.

Import the Dashboard’s Formatter

The word default after export marks the one value the file hands out when nobody asks for a name:

Language: JavaScript Filename: format.js
export default function formatReading(reading) {
  return `  ${reading.time}  ${reading.temp.toFixed(1)}`;
}

JavaScript prints 78.0 as 78, so .toFixed(1) keeps one decimal place, as Python’s :.1f does. If the formatter were Python, Dev would import it by name:

Language: Python
from format import format_reading

In JavaScript, a scratch script next to format.js imports a default with no braces at all:

Language: JavaScript Filename: try-format.js
import formatReading from "./format.js";

const reading = { time: "Wed 07:00", temp: 76.5 };
console.log(formatReading(reading));

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.