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?

1

2 Answers 2

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.

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

Comments

1

You can use a dictionary/map:

variables.js

let variables = {};

export { variables };

main.js

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

variables.x = 'whatever';

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.