Home > Enterprise >  why do interdepedent functions across modules evaluate to undefined at runtime in node javascript
why do interdepedent functions across modules evaluate to undefined at runtime in node javascript

Time:10-05

I have three javascript files

moduleA.js, moduleB.js, and index.js

moduleA.js

const {b1} = require('./moduleB');
const a1 = ()=>{
    console.log('a1 called')
};
const a2 = ()=>{
    console.log('a2 called');
    b1()
};

module.exports = {a1, a2};

moduleB.js

const {a1} = require('./moduleA');

const b1 = () => {
    console.log('b1 called');
    a1();
};
const b2 = () => {
    console.log('b2 called');
};

module.exports = {b1, b2};

index.js

const {a2} = require('./moduleA');
a2();

How come invoking a2() throws an error at runtime because a2 is undefined in node? I've not seen this type of error in another language such as Java.

Is there a solution to this apart from putting a2 in another file such as moduleC.js and call moduleC.a2()?

module dependency graph

  • Related