Example 1. I have a file test.js
const lib = {
foo: () => console.log(a)
};
lib.foo(); // can't access "a" before init
const a = 3;
Example 2. I have two files: test1.js and test2.js
const lib = require('./test2');
lib.foo(); // 3
const lib = {
foo: () => console.log(a)
};
const a = 3;
module.exports = lib;
For the same reason this is valid:
const lib = {
foo: () => console.log(a)
};
const a = 3;
lib.foo();
a exists before export, so it exists when it is called.
in the first case, you are accessing the value of "a" even before you are assigning the value for "a",
in second case, it is declared then it is used, so 2nd case works good and first case gives you error