include()
include() loads and executes another JavaScript file in the same context. Variables, functions, and state from the included file are accessible afterward.
Syntax
include(path)
Parameters
| Parameter | Type | Description |
|---|---|---|
path | string | Path to a .js file, relative to the current script |
Return Value
None (undefined). Throws an error if the file cannot be found.
Examples
Shared Layout
// header.js
print("<html><head><title>My Site</title></head><body>");
print("<nav>...</nav>");
// footer.js
print("<footer>© 2026</footer>");
print("</body></html>");
// index.js
include("./includes/header.js");
print("<h1>Welcome</h1>");
include("./includes/footer.js");
Shared Variables
// config.js
var siteName = "My App";
var version = "1.0.0";
// index.js
include("./config.js");
print(`<title>${siteName} v${version}</title>`);
Path Resolution
./file.js— relative to the main script's directory./lib/helpers.js— subdirectory/var/www/js/shared/common.js— absolute path
include() vs ES Modules
| Feature | include() | import/export |
|---|---|---|
| Shares scope | Yes | No (isolated) |
| Can output HTML | Yes | Not directly |
| Best for | Templates, layouts | Libraries, utilities |
| Execution | Immediate, inline | Module evaluation |
Errors
If the file does not exist, an error is thrown:
// Throws: Cannot include './missing.js': file not found
include("./missing.js");