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

229
Views
is it possible to change the scope of variables with initially equal scopes?

i want to know if i can make the scope of a varible go out of a module script tag, or if i can export it in some way and import in another script tag.

my current code is something like this:

<script>
    var variable1 = 'first variable :)';
    var variable2 = 'second variable :)';
</script>
<script>
    // i want to be able to access variable1 here, but not variable2
</script>

would something like this be possible?

i already tried var, let, const and window., but they make no difference. i also tried to make the first script a module, but then i couldn't access variable1, and (i think) there's no way to use import/export.

notes: i only want to separate the scripts into separate files if there is no other option.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Since variable1 and variable2 are defined in the same scope (at the top level), there's no way to access only one but not the other elsewhere - unless you changed the first script tag to something like

<script>
    var variable1 = 'first variable :)';
    (() => {
        var variable2 = 'second variable :)';
        // do stuff with variable2
    })();
    // variable2 cannot be seen outside
</script>

i only want to separate the scripts into separate files if there is no other option

It's a very good option that you should consider if you're making something reasonably professional and the code to be written isn't trivial. I highly recommend it, it makes the process of writing and maintaining code much, much easier. Yes, it does take some time to figure out and get used to, but it's worth it, IMO.

about 4 years ago · Juan Pablo Isaza Report

0

You also could use a module script and store variables using the window object:

<script type="module">
  var variable1 = 'first variable :)';
  // not accessible by others scripts
  
  window.variable2 = 'second variable :)';
  // accessible by others scripts
</script>

<script>
  console.log(window.variable2)
  setTimeout(() => console.log(variable2), 10)
</script>

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!