JavaScriptEasy
How can you share code between JavaScript files?
By FrontendPro Editorial Team Updated 8/8/2026
#JavaScript
Answer
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:
javascript
// 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:
javascript
// file1.js
module.exports = function greet() {
console.log("Hello, world!");
};
// file2.js
const greet = require("./file1.js");
greet();
