WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Node.js · Basic · question 10 of 100

What is the purpose of the ’exports’ object in Node.js?

📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

The ‘exports‘ object in Node.js is an essential aspect of the module system. Its primary purpose is to expose or export values, functions, or objects from one module so that they can be imported and used in different modules within your application. By using the ‘exports‘ object, you can create a modular code structure, where each file can have its isolated functionality, making the codebase more maintainable and easier to understand.

To illustrate this concept, let’s consider an example:

Assume that we have a simple ‘mathOperations.js‘ module that performs some basic mathematical operations:

// mathOperations.js
function add(a, b) {
    return a + b;
}

function subtract(a, b) {
    return a - b;
}

function multiply(a, b) {
    return a * b;
}

function divide(a, b) {
    return a / b;
}

Now, to make the functions available for other modules (e.g., ‘app.js‘), we use the ‘exports‘ object to export them.

// mathOperations.js
function add(a, b) {
    return a + b;
}

function subtract(a, b) {
    return a - b;
}

function multiply(a, b) {
    return a * b;
}

function divide(a, b) {
    return a / b;
}

exports.add = add;
exports.subtract = subtract;
exports.multiply = multiply;
exports.divide = divide;

Then, in another module (e.g., ‘app.js‘), you can use the ‘require()‘ function to import the ‘mathOperations‘ module and access its exported functions.

// app.js
const math = require('./mathOperations');

console.log(math.add(2, 3)); // 5
console.log(math.subtract(10, 5)); // 5
console.log(math.multiply(4, 4)); // 16
console.log(math.divide(20, 4)); // 5

By using the ‘exports‘ object, you can efficiently organize your code, share functionalities across different parts of your application, and create reusable modules.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Node.js interview — then scores it.
📞 Practice Node.js — free 15 min
📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

All 100 Node.js questions · All topics