How To Import Functions From Another File Using JavaScript

Import Functions from another file using JavaScript

In this article, you’ll learn how to import functions from another file using JavaScript with the <script> tag or the import and export keyword.

Import Functions From Another File Using JavaScript

Using the <script> tag

Only applies if you’re using HTML in addition to JS (which you probably are).

Simply add the <script> tag to your HTML file with its src attribute set to the relative address of the file containing the Functions. Please note that: Although its position in the HTML file does matter, as if a global variable is defined after your original script file, it could cause some issues.

Code (HTML):

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

Using import and export (JS Modules)

The export keyword lets you export values from a script, which includes functions, classes and variables (which can also include functions).

The import keyword lets you import any value from another script that has been exported. You can only use the import keyword in the top-level (i.e. outside of functions).

There are two types of imports: Namespace imports, Named imports and Default imports.

Default imports will get you the value from the export file with the default keyword. Note that there can only be one default value in an export file. There are many ways, including giving one a name (aliasing).


import default_name from "src";
import {default as alias_name} from "src"; // Alias

The named imports simply gets the value with the specified name.


import {name1, name2, ...} from "src";

The namespace imports returns an Object ({}) containing all the export values. Note that the default value fall under the "default" key.


import * as obj_name from "src";

You can get a function from another file by using the export keyword on the function, class or variable you wish to export and use the import keyword to get it.

One thing to note is that the element of the import script must have “type=module” as an attribute for the script to import.



export const VAL = "";
export default function _default() {


export const NAME = "";
export const DJ = () => {console.log("YO YEAH ! ! !")}
export default function sum(a,b) {
    console.log(`a + b = ${a + b}`);


import {default as log, VAL} from "./export_1.js"; // Namespace Import
import * as export2 from "./export_2.js"; // Named Import
log(); // Default
export2.default(2,4); // Default, Originally sum()


"YO YEAH ! ! !"
"a + b = 6"


To import functions from another file using JavaScript, you can choose to use one of 2 above methods.  Additionally, you can have a more in-depth learning about modules here.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *