1

I'm currently working with the discord.js library.
I guess I can call it by this name, but whenever I want to access a file, this doesn't work.

Let's say I have a file called calc.js and I want to access the main.js file and take a variable out of there using exports and require it to just take the value out of it.

But I haven't found even one way online to modify the variables and return another value to the file.
Can someone help me?

zx485
  • 28,498
  • 28
  • 50
  • 59
Tom Kark
  • 31
  • 1
  • 4
  • 2
    Possible duplicate of [Does Javascript pass by reference?](https://stackoverflow.com/questions/13104494/does-javascript-pass-by-reference) –  Dec 05 '18 at 20:13

2 Answers2

2

As noted, JavaScript doesn't pass every variable by reference. If you need to access a primitive value like a number, you could declare it as a local variable and export functions to access and modify it. Something like this rough example:

increment.js

let count = 0;

module.exports = {
  get:       () => count,
  increment: () => ++count
};

main.js

const { get, increment } = require('./increment.js');

console.log(get());
console.log(increment());
console.log(get());

Edit: You should probably not name your accessor get, as that's the key word used to describe getters in ES6. Or better yet, turn such a get function into a getter with a more suitable name.

Connor
  • 1,815
  • 3
  • 17
  • 25
1

You can use a dictionary/map:

variables.js

let variables = {};

export { variables };

main.js

const { variables } = require('./variables.js');

variables.x = 'whatever';
Wongjn
  • 8,544
  • 2
  • 8
  • 24
eliasbauer
  • 11
  • 2