# Using Functions from Other Files in JavaScript

Friday, Jan 31, 2020
JavaScript

In the need to do efficiency comparison of sorting algorithms, I wanted to organize my files/functions so I can reuse the common code without copy/paste. For example, swap() is used in many algorithms so its reasonable to keep it in one place and call it in other files as needed.

I found that there are multiple (and somewhat confusing) ways to accomplish this in JavaScript files but easiest method I found is to use the concept of local modules. Idea is to:

• create classes, objects, functions in a separate file. The items that we want to export are wrapped inside an object and assigned to module.exports.
• in the calling file, you load the module using require function.

In the simple example below, I use common.js to create a function inside a class and use module.exports to expose it. Then in main.js, I call the common.js using require and assign it to a variable.

Sweet!

NOTE: Here common.js may contain other auxillary functions that the class functions may need, but if these are not included in the module.exports object, these won't be visible to the file that uses the exported functions from this file.

//common.js -- creates a class containing functions to be used elsewhere
class Greet{
hello(){
return "Hello";
}

module.exports = {Greet};     // expose the Greet class for using elsewhere

// main.js imports functions from common.js
const common = require('./common.js');    // loads common.js module
const greet = new common.Greet();
console.log(greet.hello());            // use greet as an object to call its functions


>node main
Hello