JAVASCRIPT
JavaScript Import Statement: Syntax, Usage, and Examples
An import statement in JavaScript lets you bring code from another file into the current file. You use it to reuse functions, variables, classes, and entire modules without copying and pasting.
How to Use the Import Statement
The import statement is part of the ES Modules system (often called “ESM”). You usually place imports at the top of a file before other code runs.
Learn JavaScript on Mimo
Basic syntax
Here’s the most common pattern, importing a named export:
JSX
import { formatPrice }from"./utils.js";
console.log(formatPrice(19.99));
importstarts the statement{ formatPrice }is the named export you want"./utils.js"is the module path (relative path in this example)
Importing multiple named exports
You can import more than one export from the same module:
JSX
import { formatPrice, calculateTax }from"./utils.js";
console.log(calculateTax(50));
Importing everything as an object
If a module exports many things, you can import them into a single object:
JSX
import *as utilsfrom"./utils.js";
console.log(utils.formatPrice(12.5));
console.log(utils.calculateTax(12.5));
This can be handy when you want a neat namespace like utils.something().
Default imports
A module can export a default value, and you import it without curly braces:
JSX
import formatDatefrom"./formatDate.js";
console.log(formatDate(newDate()));
Default imports are common for single-purpose modules.
Combining default and named imports
Some modules provide a default export plus extra named helpers:
JSX
import logger, { logError }from"./logger.js";
logger("App started");
logError("Something went wrong");
Renaming imports
Sometimes the export name doesn’t match your style, or you already have a variable with that name. You can rename it using as.
JSX
import { formatPriceas price }from"./utils.js";
console.log(price(9.99));
Importing only for side effects
Some files run code immediately when imported, like setting up analytics, registering web components, or applying polyfills.
JSX
import"./setupAnalytics.js";
No variables are imported here, the file just runs.
Importing from packages
In Node.js or bundler setups (like Vite or Webpack), you can import from installed packages:
JSX
import { nanoid }from"nanoid";
console.log(nanoid());
This works because the package is in your node_modules.
When to Use the Import Statement
Imports show up almost everywhere once you start organizing your code into files. Here are a few common situations where the import statement is the right tool.
1) Splitting large projects into smaller files
One huge file becomes hard to read fast. Imports let you separate concerns, like putting UI code in one module, API logic in another, and validation in a third.
2) Reusing helper functions across multiple features
A date formatting helper, a currency formatter, or a string cleanup function shouldn’t be rewritten ten times. Import it where you need it.
3) Sharing types and constants
When multiple files rely on the same values, imports help you keep everything consistent.
4) Building apps with bundlers or frameworks
React, Vue, Svelte, and modern tooling all rely heavily on module imports. Your components, styles, and utilities usually come in through imports.
5) Writing cleaner test code
Testing libraries often use imports to pull in the function you want to test, plus testing helpers, mocks, or fixtures.
Examples of the Import Statement
Example 1: Importing a utility function
Say you have a small helper for formatting names.
nameUtils.js
JSX
exportfunctionformatName(firstName, lastName) {
return`${firstName.trim()}${lastName.trim()}`;
}
app.js
JSX
import { formatName }from"./nameUtils.js";
console.log(formatName("Samira","Nolan"));
// "Samira Nolan"
The helper stays in one place, and you can reuse it anywhere.
Example 2: Importing a class
Classes often live in their own file to keep the codebase tidy.
Timer.js
JSX
exportdefaultclassTimer {
constructor(seconds) {
this.seconds = seconds;
}
start() {
console.log(`Starting timer for ${this.seconds} seconds`);
}
}
main.js
JSX
importTimerfrom"./Timer.js";
const workoutTimer =newTimer(30);
workoutTimer.start();
This reads nicely, and it’s easy to find where Timer comes from.
Example 3: Importing configuration constants
Centralizing configuration avoids repeating numbers and strings across files.
config.js
JSX
exportconstAPI_URL ="https://api.example.com";
exportconstTIMEOUT_MS =5000;
fetchUser.js
JSX
import {API_URL,TIMEOUT_MS }from"./config.js";
asyncfunctionfetchUser(id) {
const controller =newAbortController();
setTimeout(() => controller.abort(),TIMEOUT_MS);
const res =awaitfetch(`${API_URL}/users/${id}`, {
signal: controller.signal
});
return res.json();
}
If the API URL changes, you update one file and move on with your day.
Example 4: Importing everything as a module object
This is a nice option when you don’t want to import a long list of names.
mathTools.js
JSX
exportfunctionadd(a, b) {
return a + b;
}
exportfunctionsubtract(a, b) {
return a - b;
}
calculator.js
JSX
import *as mathfrom"./mathTools.js";
console.log(math.add(3,4));// 7
console.log(math.subtract(9,2));// 7
Using math. makes it very obvious where functions come from.
Example 5: Importing a package function
If you’re working in a project with package installs, imports help you use third-party tools.
JSX
import debouncefrom"lodash.debounce";
functionhandleResize() {
console.log("Window resized");
}
window.addEventListener("resize",debounce(handleResize,300));
This is common in real apps, especially for performance helpers.
Learn More About the Import Statement
Named exports vs default exports
JavaScript modules support two main export styles:
Named export
JSX
exportfunctiongreet(name) {
return`Hi, ${name}!`;
}
Imported with curly braces:
JSX
import { greet }from"./greet.js";
Default export
JSX
exportdefaultfunctiongreet(name) {
return`Hi, ${name}!`;
}
Imported without braces:
JSX
import greetfrom"./greet.js";
A good rule of thumb:
- Use named exports when a file exports multiple things
- Use a default export when the file has one main purpose
Import paths and file extensions
In browsers, module imports usually require the file extension:
JSX
import { sum }from"./math.js";
In Node.js with ES modules enabled, you often need the extension too.
Bundlers can sometimes resolve extensions automatically, but relying on that can confuse new teammates, so adding .js is a nice habit.
Static imports vs dynamic imports
The regular import statement is static, meaning it must be at the top level of the module.
This works:
JSX
import { formatPrice }from"./utils.js";
This does not:
JSX
// ❌ Syntax error
if (true) {
import { formatPrice }from"./utils.js";
}
If you need to load a module conditionally, use a dynamic import instead:
JSX
asyncfunctionloadChart() {
constmodule =awaitimport("./chart.js");
module.renderChart();
}
Dynamic imports return a promise, so await comes in handy.
Importing JSON files
Some environments allow importing JSON directly, but support depends on where your code runs and how your tooling is set up.
You’ll often see JSON loaded through fetch in browsers:
JSX
asyncfunctionloadData() {
const res =awaitfetch("./data.json");
return res.json();
}
Or imported via tooling in modern app setups.
Common import mistakes
Importing the wrong name
JSX
// utils.js exports formatPrice, not format
import { format }from"./utils.js";// undefined import
Fix it by matching the export name:
JSX
import { formatPrice }from"./utils.js";
Mixing up default vs named imports
JSX
// greet.js exports default
import { greet }from"./greet.js";// wrong
Fix:
JSX
import greetfrom"./greet.js";
Incorrect relative path
JSX
import { helper }from"utils.js";// missing ./ or ../
Fix:
JSX
import { helper }from"./utils.js";
Summary
The import statement helps you reuse code by bringing exports from other modules into the current file. You can import named exports, default exports, entire modules, and even load modules dynamically. Once you start splitting your code into smaller files, imports become the glue that holds everything together.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot