Question

How to Include One JavaScript File in Another JavaScript File

javascriptfileimportinclude

Question

How can I use code from one JavaScript file inside another JavaScript file, similar to how @import works in CSS?

For example, if I have one JavaScript file that defines reusable functions or variables, what is the correct way to make those available in another JavaScript file?

Short Answer

By the end of this page, you will understand that JavaScript does not traditionally "include" one file inside another the way CSS uses @import. Instead, JavaScript code is shared through file loading in HTML or through module systems such as ES modules. You will learn the difference between classic script loading and import/export, when to use each approach, and how this works in real projects.

Concept

JavaScript files are not usually inserted into each other by writing a special include statement inside the file itself. Instead, JavaScript code is made available in one of two common ways:

  1. Classic script loading using multiple <script> tags in an HTML file.
  2. Modules using export in one file and import in another.

In older JavaScript, if you loaded multiple files in an HTML page, they shared the same global scope. That meant one file could define a function and another file could use it, as long as the files were loaded in the correct order.

In modern JavaScript, the preferred approach is ES modules. A module lets you explicitly choose what a file exposes and what another file imports. This makes code easier to understand, test, and maintain.

Why this matters:

  • It helps you organize code across multiple files.
  • It avoids putting too many variables in the global scope.
  • It makes dependencies clear.
  • It is the standard approach in modern frontend and backend JavaScript.

So the real concept is not "including a file inside another file," but sharing code between files in a structured way.

Mental Model

Think of each JavaScript file as a toolbox.

  • In the old style, all toolboxes are dumped onto one shared workbench. If one file adds a hammer, another file can use it, but only if the hammer was placed there first.
  • In the modern module style, each toolbox is closed by default. If you want another file to use a tool, you must label it with export. The other file must then explicitly request it with import.

This makes it much easier to know where each tool came from and prevents the workbench from becoming cluttered.

Take Quiz

Syntax and Examples

1. Classic script loading

If you are working in a browser without modules, you can load multiple JavaScript files from HTML.

<script src="helpers.js"></script>
<script src="app.js"></script>

helpers.js

function greet(name) {
  return `Hello, ${name}`;
}

app.js

console.log(greet("Sam"));

Because helpers.js is loaded first, app.js can use greet().

2. Modern ES modules

This is the preferred modern approach.

helpers.js

export function greet(name) {
  return `Hello, ${name}`;
}

app.js

import { greet } from './helpers.js';

console.log(greet("Sam"));

In HTML, load the entry file as a module:

<script type="module" src="app.js"></script>

3. Default export example

math.js

export default function add(a, b) {
  return a + b;
}

app.js

import add from './math.js';

console.log(add(2, 3));

Explanation

  • Use classic script tags for simple older setups.
  • Use ES modules for modern JavaScript projects.
  • With modules, file paths matter and usually must include ./ and the file extension in browser code.

Step by Step Execution

Consider this module example:

// helpers.js
export function double(number) {
  return number * 2;
}
// app.js
import { double } from './helpers.js';

const result = double(5);
console.log(result);

Here is what happens step by step:

  1. The browser loads app.js because it was included with:

    <script type="module" src="app.js"></script>
    
  2. JavaScript sees this line:

    import { double } from './helpers.js';
    
  3. It loads helpers.js.

  4. In helpers.js, it finds an exported function named double.

  5. That function becomes available inside app.js.

  6. This line runs:

    const result = double(5);
    
  7. double(5) returns 10.

  8. result stores 10.

  9. console.log(result) prints:

    10
    

The important idea is that app.js does not copy and paste the other file. It imports a specific exported value from it.

Real World Use Cases

This concept is used everywhere in real JavaScript applications.

  • Utility functions: Put shared helpers like formatting dates or validating email addresses in one file and import them where needed.
  • API code: Keep network request logic in a separate file such as api.js and use it in UI components.
  • Configuration: Store constants like API URLs or app settings in one module.
  • UI components: Split large frontend apps into many files, each exporting related code.
  • Data processing scripts: Reuse parsing or transformation functions across multiple scripts.
  • Node.js projects: Import functions, classes, or configuration files into route handlers, services, and utilities.

Example:

// config.js
export const API_BASE_URL = 'https://api.example.com';
// userService.js
import { API_BASE_URL } from './config.js';

console.log(`${API_BASE_URL}/users`);
Take Quiz

Real Codebase Usage

In real projects, developers rarely keep everything in one file. Instead, they break code into focused modules.

Common patterns include:

Guard clauses and validation

export function validateUser(user) {
  if (!user) {
    throw new Error('User is required');
  }

  if (!user.email) {
    return false;
  }

  return true;
}

This can then be imported wherever user data is checked.

Centralized configuration

// settings.js
export const MAX_RETRIES = 3;
export const TIMEOUT_MS = 5000;

Grouped utility modules

// stringUtils.js
export function capitalize(text) {
  return text.charAt(0).toUpperCase() + text.slice(1);
}

export function slugify(text) {
  return text.toLowerCase().replaceAll(' ', '-');
}

Separation of concerns

A real codebase often separates:

  • UI logic
  • API calls
  • validation
  • utility functions
  • configuration
  • state management

Each part lives in its own file and is imported where needed.

Why teams prefer modules

  • clearer dependencies
  • fewer global variables
  • easier testing
  • better file organization
  • simpler refactoring

Common Mistakes

1. Expecting an @import-style include inside plain JavaScript

JavaScript does not work like CSS in this way. You usually either:

  • load files from HTML, or
  • use import/export

2. Loading files in the wrong order with classic scripts

Broken example:

<script src="app.js"></script>
<script src="helpers.js"></script>
// app.js
console.log(greet("Sam"));

This fails because greet is not defined yet.

Fix:

<script src="helpers.js"></script>
<script src="app.js"></script>

3. Forgetting to export

Broken example:

// helpers.js
function greet(name) {
  return `Hello, ${name}`;
}
// app.js
import { greet } from './helpers.js';

This fails because greet was never exported.

Fix:

export function greet(name) {
  return `Hello, ${name}`;
}

4. Forgetting the correct path

Broken example:

import { greet } from 'helpers.js';

In browser ES modules, use a relative path when importing local files:

import { greet } from './helpers.js';

5. Mixing default and named imports incorrectly

Broken example:

// math.js
export default function add(a, b) {
  return a + b;
}
import { add } from './math.js';

Fix:

import add from './math.js';

6. Trying to use import in a non-module script

Broken HTML:

<script src="app.js"></script>

If app.js contains import, load it like this:

<script type="module" src="app.js"></script>

Comparisons

ApproachHow it worksBest forProsCons
Classic <script> tagsLoad files in HTML; all share global scopeVery small or older browser examplesSimple to start withOrder matters, globals can clash
ES modules (import/export)Files explicitly share exported valuesModern frontend and backend JavaScriptClear dependencies, modular codeRequires module-aware environment
Copy-pasting codeDuplicate logic across filesAlmost never a good choiceFast for a quick testHard to maintain, error-prone

Named export vs default export

TypeExport syntaxImport syntaxWhen to use
Named exportexport function greet() {}import { greet } from './file.js'When exporting multiple values
Default exportexport default function greet() {}import greet from './file.js'When a file has one main thing to export

Global script vs module mindset

StyleVisibilityDependency clarity
Global scriptsShared across files if loaded correctlyLower
ModulesPrivate by default unless exportedHigher
Take Quiz

Cheat Sheet

Quick reference

Classic browser loading

<script src="file1.js"></script>
<script src="file2.js"></script>
  • Files are loaded in order.
  • Earlier files can define globals used by later files.
  • Avoid this for large applications.

ES modules

Export from one file:

export const value = 123;
export function greet(name) {
  return `Hello, ${name}`;
}

Import into another file:

import { value, greet } from './helpers.js';

Default export

export default function add(a, b) {
  return a + b;
}
import add from './math.js';

Browser module script

<script type="module" src="app.js"></script>

Rules to remember

  • JavaScript does not have a CSS-style @import for plain file inclusion.
  • Use HTML script tags or ES modules.
  • In classic scripts, load dependencies first.
  • In ES modules, export values before importing them.
  • Use ./ for local file paths in browser imports.
  • Default imports do not use curly braces.
  • Named imports do use curly braces.

FAQ

Can I include one JavaScript file directly inside another?

Not in the old CSS-like sense. The usual approaches are loading both files in HTML or using ES modules with import and export.

What is the modern way to share code between JavaScript files?

Use ES modules. Export values from one file and import them into another.

Why does my import statement not work in the browser?

Common reasons include missing type="module", wrong file path, or forgetting to export the value.

Do I need to include .js in import paths?

In browser ES modules, yes, you usually include the file extension for local files.

What is the difference between named and default exports?

Named exports let a file expose multiple values. A default export is usually the main value from a file.

Can multiple files use the same helper function?

Yes. Put the helper in one module, export it, and import it wherever needed.

Is using global variables across script files a good idea?

Usually no. It works in simple cases, but modules are safer and easier to maintain.

Take Quiz

Mini Project

Description

Build a small reusable utility setup with two JavaScript files. One file will contain helper functions, and the other will import and use them. This demonstrates the modern way to share code between files without relying on global variables.

Goal

Create a simple app that imports functions from another file and uses them to format and process text.

Requirements

  • Create one file that exports at least two helper functions.
  • Create a second file that imports and uses those functions.
  • Load the second file in the browser as a module.
  • Display the results in the console.
  • Use correct relative import paths.
Take Quiz

Keep learning

Related questions

View more