How can you share code between files?
This depends on the JavaScript environment.
On the client (browser environment), as long as the variables/functions are declared in the global scope (window), all scripts can refer to them. Alternatively, adopt the Asynchronous Module Definition (AMD) via RequireJS for a more modular approach.
On the server (Node.js), the common way has been to use CommonJS. Each file is treated as a module and it can export variables and functions by attaching them to the module.exports object.
ES2015 defines a module syntax which aims to replace both AMD and CommonJS. This will eventually be supported in both browser and Node environments.
References
Adapted from the Front End Interview Handbook by Yangshun Tay and contributors (MIT License). Source
Spotted a mistake or a rights concern? Report an issue