Srki
Srki

Reputation: 385

Change variable from different js

I am new to JS and am currently attempting to make some of my own projects. For one of them, I need to have the same variable in two scripts, I am using NodeJS. For example I want...

var text1
text1 = 'first text'
//in script1.js

to change variable text1 to 'first text' both in script1.js and script2.js and vice versa. My first thought was to store text1 in a txt document and read/write to it, but I think that this won't be so good. Any suggestions on how to do this without saving in a txt document would be appreciated. How to do it without saving in a txt, I'm looking for any solution that works.

Upvotes: 1

Views: 98

Answers (1)

Ridwan Malik
Ridwan Malik

Reputation: 796

You have to add the keyword export before it

var text1
text1 = 'first text'
export text1

Then on the other file, you have to import it

import { text1 } from './script1.js'

console.log( text1 )

You can export multiple items and make a function to change that variable.

var text1 = 'first text';

const change = (value) => text1 = value;

export { text1 , change }

and then

import { text1 , change } from './script1.js';

console.log( text1 )

change('hello world!')

console.log( text1 )

If you want to export a single variable from a single file you can also make it a default export by adding the default keyword after the export keyword

var text1
text1 = 'first text'
export default text1

Then you don't need to put the curly braces { } in the import statement

import text1 from './script1.js'

console.log( text1 )

Hope you get your answer. 😊😊

Upvotes: 3

Related Questions