DivDisable
DivDisable

Reputation: 11

module.exports and scope in javascript

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;
Question: Why second example is valid?

Upvotes: 0

Views: 153

Answers (2)

Christopher Styles
Christopher Styles

Reputation: 31

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

Upvotes: 0

ᴓᴓᴓ
ᴓᴓᴓ

Reputation: 1176

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.

Upvotes: 1

Related Questions