0

module.exports.variable vs module.exports={variable}

Consider the code below from fileOne.js

module.exports = {
    x,
    v
}

async function v(){
    return "v"
}

var x = "x"

fileTwo.js

const y = require('./fileOne');

console.log(y.x, y.v());
// returns undefined and "v".

If I change fileOne.js code to:

module.exports = {
    //x,
    v
}

async function v(){
    return "v"
}
module.exports.x = "x"

... the code from fileTwo.js logs x and v to the console.

What is the difference between module.exports.variable and module.exports={variable} and why does the former work for variables but the latter does not?

YulePale
  • 6,688
  • 16
  • 46
  • 95
  • 2
    ...The difference isn't really in the syntax of your exports - it's just the age old [hoisting](https://stackoverflow.com/questions/7506844/javascript-function-scoping-and-hoisting) at play. When you export `x` *before* you assign it, you get just that - an `undefined` because the assignment hasn't run yet. Function hoisting with `v` *will* ensure declaration + assignment happens before referencing the variable. When you do `module.exports.x = "x"` then you export the assigned value. If you move `module.exports = {x, v}` to the *bottom* of the file, it will work correctly. – VLAZ Jul 02 '20 at 17:27
  • 1
    Related: [var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/q/336859) | [Difference between variable declaration syntaxes in Javascript (including global variables)?](https://stackoverflow.com/q/4862193) | [Are variables declared with let or const not hoisted in ES6?](https://stackoverflow.com/q/31219420) | [Hoisting variables in JavaScript](https://stackoverflow.com/q/36246124) | [Order of hoisting in JavaScript](https://stackoverflow.com/q/28246589) – VLAZ Jul 02 '20 at 17:42
  • @VLAZ Your comments have made me understand it really well. Thank you. – YulePale Jul 02 '20 at 18:19

0 Answers0