javascript · level 3 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Named exports keep their names; a takes any name.
A module can share many named exports, like export const rate. Importing files must use those exact names: import { add, rate } from "./maths.js". Clash with a name you already have? Give it an : import { add as plus }.
A module can also have one default export, its main thing: export default class Cart. Importing files name it whatever they like: import ShoppingCart from "./cart.js". Our stand-in mirrors this with destructuring, where add: plus gives the alias.
const maths = (() => {
const add = (a, b) => a + b;
const rate = 0.2;
return { add, rate };
})();
const { add: plus, rate } = maths;
const add = "a name already taken";
console.log(plus(2, 3), rate, add); import * as maths from "./maths.js" gathers every named export into one object, much like this stand-in.
guess first
One alias and one name that is not there. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const units = (() => {
const toKm = (miles) => miles * 1.6;
const toMiles = (km) => km / 1.6;
return { toKm, toMiles };
})();
const { toKm: milesToKm, toMetres } = units;
console.log(milesToKm(10));
console.log(typeof toMetres);
your turn
Your turn. Dodge a name clash with an alias.
format is already taken. Choose a new name, such as formatDate, and type it in both blanks.
fix it
The cart will not build. Can you fix it?
- The module's main export is stored under the key
default. Which key does line 9 ask for? import Cart fromreally means: takedefaultand call itCart.- Change line 9 to
const { default: Cart } = cartModule;, then press run.
nailed it
you can share code the professional way. :D
- Named exports are imported by name, in curly brackets.
- A default export is the main thing, named freely.
- An alias dodges a clash:
asor a colon.
new words in your collection
- named export
- default export
- alias
This lesson isn’t saved. A free account remembers every lesson you finish.