prabin badyakar
prabin badyakar

Reputation: 1726

How to get variable value from another js file

I've JavaScript file named Second.js which contains variable named page.

Second.js:

var page = 1;

How can I retrieve that value, i.e page, from another JavaScript named one.js?

Upvotes: 2

Views: 29988

Answers (5)

Shah Nawaz
Shah Nawaz

Reputation: 396

An other way to get a value from another .js file is saving the variable in the browser:

a.js
var myemail="[email protected]";
localStorage.setItem("email",myemail);

Now this variable is saved in browser. If we want to get this variable in another file we use:

b.js
var x=localStorage.getItem("email");
alert(x) // [email protected]

Upvotes: 3

cheersphilip
cheersphilip

Reputation: 113

There are two ways of doing this: load the scripts in the order you want to access them, or don't start executing your scripts until the page the has loaded (recommended, as this ensures that everything is definitely loaded!). Either way you can reference your variables as if they were in the same file - you do not need to re-declare them with 'var'.

Upvotes: 0

Michael Voznesensky
Michael Voznesensky

Reputation: 1618

They both have to be included into the same HTML file. Make sure both are in, and loaded, and then it is as if all your javascript exists in one single, massive, JS file!

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074028

All JavaScript on the page executes in the same overall environment, so if page is a global in Second.js, you can use it from any other JavaScript you load on the page. E.g.:

<script src="Second.js"></script>
<script src="SomeOtherFile.js"></script>

Provided, again, that page is a global, you can use it from SomeOtherFile.js (just referencing it as page, no qualifiers).

Or even:

<script src="Second.js"></script>
<script>
    alert(page); // "1"
</script>

If page isn't a global, then you'll have to modify Second.js in some way to make the page variable or value available to other scripts. You can do that by making it global, of course, or you can use an Asynchronous Module Definition loader to avoid having bunches of globals around and manage dependencies. (AMD may be overkill for what you're doing, or not, we don't have a lot of context here.)

Upvotes: 0

cherouvim
cherouvim

Reputation: 31903

If you really want variable visibility between different scripts you can attach the variable on the window. e.g:

script 1:

window.page = 1;

script 2:

alert(page);

Make sure you don't use very simple variable names (e.g such as page) to avoid possible collisions. A good practice is to attach an array of your application name on the window and work with that, being sure that you'll not affect anything on the "global scope". e.g:

window.MY_APP = {
  page: 1,
  foo: 'bar',
  whatever: [1, 2, 3],
  example: {
    name: 'john',
    surname: 'smith'
  }
};

Upvotes: 0

Related Questions