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

137
Views
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.

about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

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. ๐Ÿ˜Š๐Ÿ˜Š

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!