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

385
Views
How to send a data to one Javascript script file to another Javascript script file

I want to send a = 5 to another js file and add them,the other file should have a type = "module" in it.

<script>
  let a = 5;
  // file 1
</script>
    
<script type="module">
  console.log(a+5)
  // file 2
  // I need (type = "module") in file 2
</script>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Because modules run and load asynchronously, the non-module script will run first, which will make things a bit difficult. I'd put the non-module script in a separate file - this will allow you to use the defer attribute on its script tag (defer has no effect on inline scripts). Since deferred scripts run in the order in which they appear in the DOM, you can then have the module expose something globally, first, and then have the deferred non-module call that global function.

<script src="file-2.js" type="module"></script>
<script defer src="file-1.js"></script>
// file-2.js
window.doSomethingWithA = (a) => {
  console.log(a);
}
// file-1.js
window.doSomethingWithA(5);

But a better approach would be to put all your scripts into modules - it'll make things a lot easier to manage when the code becomes of any reasonable size. It's also counter-productive for a module to make something global - one of the big selling points of modules is that they can be made to be completely self-contained.

Another approach, without relying on script order, would be to have the non-module script listen for a load event on the module script, then call the global function.

about 4 years ago · Juan Pablo Isaza Report

0

For this answer assume both the files are in the same folder:

Folder
   |- firstFile.js
   |- secondFile.js

add export in firstFile.js

//firstFile.js
export let a = 5;

and import in secondFile.js

//secondFile.js
import {a} from './firstFile.js'
console.log(a)

result:
5
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!