0

I am facing a situation where I have to access a javascript variable from the second file to the first one. But unfortunately, I don't want to rearrange the script order (Because this is the situation).

In HTML:

<body>
  <script src="frist.js"></script>
  <script src="second.js"></script>
</body>

In frist.js:

console.log(foo); // Got access from second file

In second.js:

const foo = "Access me" // Trying to access from first.js
Biswajit Biswas
  • 104
  • 1
  • 8
  • You are doing something wrong..Could pls explain more about your requirement... – aravind May 21 '20 at 03:51
  • Try exporting the second.js file and then import it on the first.js file. Hope this will solve the problem. – Jakaria Ridoy May 21 '20 at 03:51
  • I not using any js framework or nodeJS only pure HTML and JS @JakariaRidoy – Biswajit Biswas May 21 '20 at 03:53
  • @BiswajitBiswas Still, you can do this as JavaScript provides the export and import module. Here is the solution you can take a look [link](https://codesandbox.io/s/export-import-javascript-vkbc8) – Jakaria Ridoy May 21 '20 at 04:12
  • Does this answer your question? [Can I access variables from another file?](https://stackoverflow.com/questions/3244361/can-i-access-variables-from-another-file) – Dan O May 21 '20 at 04:15
  • ah, I missed that you are not able to rearrange script order. sorry! – Dan O May 21 '20 at 04:15
  • @DanO Yes it does. Solution link [codesandbox.io](https://codesandbox.io/s/export-import-javascript-vkbc8?file=/src/index2.js) – Jakaria Ridoy May 21 '20 at 04:24

2 Answers2

0

You can use javascript function setTimeout in your first.js file.

setTimeout(function(){
    alert(foo);
},3000);
0

first.js

import foo from "./second.js";
console.log(foo);

second.js

const foo = "Jakaria";
export default foo;

Hope this solves the problem. And I also provide you the Sandbox link in the comment box above for a hands-on look.

Jakaria Ridoy
  • 92
  • 1
  • 8