Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!