0

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?

2
  • 5
    Because you're calling lib.foo() after const a Commented Jul 11, 2022 at 16:02
  • Your second example with a module would even be valid if you did module.exports.foo = () => console.log(a); const a = 3; where you export the function before initialising the constant. All that matters is that it's not called before a is initialised. Commented Jul 11, 2022 at 16:09

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.