Since ECMAScript 6 (or ES6) you can use the export or import statement in a JavaScript file to export or import variables, functions, classes or any other entity to/from other JS files.
For example, let's suppose you've two JavaScript files named "main.js" and "app.js" and you want to export some variables and functions from "main.js" to "app.js". Then in "main.js" file you need to write the export statement (line no-9) as shown in the following example:
let msg = "Hello World!";
const PI = 3.14;
function addNumbers(a, b){
return a + b;
}
// Exporting variables and functions
export { msg, PI, addNumbers };
And in "app.js" file you need to write the import statement (line no-1) as shown here:
Alternatively, you can use the jQuery getScript() method to load a JS file from the server, then execute it with a sigle line of code. Let's suppose you have a JS file "test.js" with the following code.
// Defining variables
var str = "Hi there!";
var num = 15;
// Defining a function
function multiplyNumbers(a, b){
return a * b;
}
Now you can load this "test.js" file in your script using the getScript() method, like this:
Use the
exportandimportStatementSince ECMAScript 6 (or ES6) you can use the
exportorimportstatement in a JavaScript file to export or import variables, functions, classes or any other entity to/from other JS files.For example, let's suppose you've two JavaScript files named "main.js" and "app.js" and you want to export some variables and functions from "main.js" to "app.js". Then in "main.js" file you need to write the
exportstatement (line no-9) as shown in the following example:And in "app.js" file you need to write the import statement (line no-1) as shown here:
Alternatively, you can use the jQuery getScript() method to load a JS file from the server, then execute it with a sigle line of code. Let's suppose you have a JS file "test.js" with the following code.
Now you can load this "test.js" file in your script using the getScript() method, like this:
need an explanation for this answer? contact us directly to get an explanation for this answer