0

I found that this function could not access "arr" even though it is in the same scope

const arr = [1, 2, 3]
const foo = require("./test2")
// const foo = () => console.log(arr[0])
foo()

> ReferenceError: arr is not defined
// ***test2.js definition for reference***
module.exports = () => console.log(arr[0])

But when I declare the same function in the main module, it works just fine.

const arr = [1, 2, 3]
// const foo = require("./test2")
const foo = () => console.log(arr[0])
foo()

> 1 

Both are identical functions, except one declaration is from a module, why is one able to access the global variable while the other isn't? Is it something in the way Node executes JS code? Can anyone explain this behavior?

pycode93
  • 18
  • 2

1 Answers1

1

In NodeJS, all files are modules. A variable you define in one file isn't readily accessible to another file just because it was imported first.

If you're coming from using script tags on the client side, it may seem like all you have to do is put the scripts in the right order (or import modules in the right order) in order to get access to different pieces of code. However, in NodeJS, each file is its own entity. It doesn't just turn into one long, global piece of JavaScript like it does in the browser.

If you want code from one file in NodeJS to work in another file, you have to define what you want to export from that file and make sure you're importing it into the file you'd like to use it in. In your example, arr[0] doesn't exist in test2.js. That's why you're getting an error that arr is not defined. If you want to use arr in the function you're importing from test2.js, you can do the following:

/*  test2.js  */
module.exports = (x) => console.log(x)

/*  main file */
const arr = [1, 2, 3]
const foo = require("./test2")

foo(arr[0])
// > 1
isaacsan 123
  • 1,045
  • 8
  • 11