How to Include a JavaScript File in another JavaScript File

Answer: Use the export and import Statemen

ECMAScript 6 or ES6 allows you to use the JavaScript  exportimport  statement to import or export variables, classes, or other entities to/from other JS file.

Let’s say, for example, you have two JavaScript files called “main.js” and “app.js”. You want to export certain variables and functions between “main.js” and “app.js”. Next, in the “main.js” file, write the  export  statement (line number 9) as shown in this example.

let msg = "Hello World!";
const PI = 3.14; 
 
function addNumbers(a, b){
    return a + b;
}
 
// Exporting variables and functions
export { msg, PI, addNumbers }

You will need to add the import  statement (line 1) in the “app.js file.

import { msg, PI, addNumbers } from './main.js';
 
console.log(msg); // Prints: Hello World!
console.log(PI); // Prints: 3.14
console.log(addNumbers(5, 16)); // Prints: 21

Alternativly, you can use jQuery  getScript() to load a JS files from the server and then execute it using a single line. Let’s say you have a JS folder called “test.js” and the following code.

// Defining variables
var str = "Hi there!";
var num = 15;
 
// Defining a function
function multiplyNumbers(a, b){
    return a * b;
}

You can now load the “test.js” file into your script by using the  getScript()  method.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Load JS File Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
    <script>
    var url = "test.js";
    
    $.getScript(url, function(){
        $(document).ready(function(){
            console.log(str); // Prints: Hi there!
            console.log(num); // Prints: 15
            console.log(multiplyNumbers(4, 25)); // Prints: 100
        });
    });
    </script> 
</body>
</html>