The import statement
Learn to import values from a module with named and default imports.
The import statement
To bring values into a module you use the import statement. Named exports go inside curly braces, by name.
import { add, subtract } from './calc.js';A path starting with ./ means a file in the same folder. Ending with a semicolon is a good habit.
After importing you can use these values like any local binding.
Default import
When importing a default export you skip the curly braces; you choose the name.
import calculate from './calc.js';You can combine named and default imports in one line:
import calculate, { add, subtract } from './calc.js';To run a module just for its side effects, write import './setup.js';.
Exercise Named import and call
Import add and subtract from ./calc.js with a named import. Then log the result of add(2, 3) with console.log.
Show example solution
Put add and subtract inside curly braces with path './calc.js'. Then call add.
Example solution:
import { add, subtract } from './calc.js';
console.log(add(2, 3));
Test yourself
-
What does import { add } from './calc.js' import?
import { add } from './calc.js';- the default export
- the whole module
- the file itself
- the named export add
Show answer
the named export add — Correct! Curly braces indicate a named export.
-
Complete the named import
import { ____ } from './calc.js';Show answer
import { add } from './calc.js'; -
Match the import types
- import { x }
- named import
- import x
- default import
- import './f.js'
- for side effects
- from './f.js'
- source file
-
Complete the default import
import ____ from './calc.js';Show answer
import calculate from './calc.js';