-1

I want to know about using variables in different JavaScript files

This is first file's code:

var volume, time, data1, data2;

volume = prompt("What is the total injection Volume?");
time = prompt("What is the total injection Time?");
data1 = Number(volume);
data2 = Number(time);

This is second file's code:

var data3, data4, data5;
data3 = 100;
data4 = (data1)*(20/data2); 
data5 = ((data3-data4)/data4)*100;

I want to calculate data4, however, I don't know how to use variables (such as data1 and data2) in the other file.

DenverCoder1
  • 2,253
  • 1
  • 10
  • 23
  • 1
    Separate files do not neccessarily mean separate programs. I think you might need to go through some basic examples/tutorials. – Rob Mar 08 '20 at 08:42
  • I know the example seems so simple. But, I have to separate data3,4,5 with prompt. – Kim JaeWoo Mar 08 '20 at 09:13
  • As long as `first.js` is loaded before `second.js`, you can simply use the variables like you're doing now. – Angel Politis Mar 08 '20 at 10:29

2 Answers2

0

As long as you keep a correct hierarchy, you can use the first file js' vars (globally scoped) in the second as well, without any special treatment.

Take into account that if you load the first script asynchronously, you'd need to wait for it to be loaded before using any of its vars.

  • It's really helpful for me. However, this segment of the codes are just a part of my codes. More specifically, my code is simply like this. (A.html -> a.js -> b.js -> B.html) So I have to connect a.js and b.js to use same variables. I just want to use same variables. Of course I already read books and find search engines. Many people suggested that using import/export and src(js&html) might be possible. However, I want to connect "javascript file & javascript file", not "javascript file & html file" or "html file & html file". – Kim JaeWoo Mar 08 '20 at 13:50
  • I'd recommend you to take a look at this: https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file – levisnkyyyy Mar 09 '20 at 09:11
0

A good bit of time has passed since I posted my original question. Now it seems very mediocre; however, I think I have to reply the answer of my questions to compensate for my mistakes.

I use substring and split references. For example,

var paramsList = location.search.substring(1).split("&");

This means that we can split sent URL by '&', and delete strings until '?'. So the paramsList[] became array. We can use it like array like this.

for(var i=0;i<paramsList.length;i++) {
                var paramValue = paramsList[i].split('=');

                if(paramValue[0] == paramsNum) { 
                    var paramResult = paramValue[1].split('+');
                    return paramResult; 
                }
            }