Quiz

How can you share code between JavaScript files?

Topics
JavaScript
Edit on GitHub

TL;DR

To share code between JavaScript files, you can use modules. In modern JavaScript, you can use ES6 modules with export and import statements. For example, you can export a function from one file and import it into another:

// file1.js
export function greet() {
console.log('Hello, world!');
}
// file2.js
import { greet } from './file1.js';
greet();

Alternatively, in Node.js, you can use module.exports and require:

// file1.js
module.exports = function greet() {
console.log('Hello, world!');
};
// file2.js
const greet = require('./file1.js');
greet();

Using ES6 modules

Exporting code

To share code, you can use the export keyword to export variables, functions, or classes from a module:

// utils.js
export function add(a, b) {
return a + b;
}
export const PI = 3.14;

Importing code

You can then import the exported code in another file using the import keyword:

// main.js
import { add, PI } from './utils.js';
console.log(add(2, 3)); // 5
console.log(PI); // 3.14

Default exports

You can also export a single default value from a module:

// math.js
export default function subtract(a, b) {
return a - b;
}

And import it without curly braces:

// main.js
import subtract from './math.js';
console.log(subtract(5, 2)); // 3

Using CommonJS modules in Node.js

Exporting code

In Node.js, you can use module.exports to export code:

// utils.js
module.exports.add = function (a, b) {
return a + b;
};
module.exports.PI = 3.14;

Importing code

You can then import the exported code using require:

// main.js
const utils = require('./utils.js');
console.log(utils.add(2, 3)); // 5
console.log(utils.PI); // 3.14

Exporting a single value

You can also export a single value:

// math.js
module.exports = function subtract(a, b) {
return a - b;
};

And import it directly:

// main.js
const subtract = require('./math.js');
console.log(subtract(5, 2)); // 3

Further reading

Edit on GitHub