doremi
doremi

Reputation: 15329

Why does module.exports still work when called before defining exported properties?

I have this code:

var config = module.exports = {};

config.foo = {...};

This works find, but I'd like to understand why.

I feel like I can wrap my head around the implementation below because it appears to make more sense to export config, not set config equal to module.exports.

var config = {};
config.foo = {...};

module.exports = config;

Can someone shed some light on this?

Upvotes: 1

Views: 46

Answers (1)

lshearer
lshearer

Reputation: 416

var config = module.exports = {}; 

is equivalent to

var config = (module.exports = {}); 

and

module.exports = {};
var config = module.exports;

The value getting exported here is {}. Because config and module.exports are just references to the same object {}, the property foo can still get added to that object via either variable module.exports or config.

Upvotes: 2

Related Questions