16

I tried the following, trying to pass a variable from one JavaScript file to another JavaScript variable. My first JavaScript file:

var x = "sachin";

My other JavaScript file can't access that x variable value. How do I solve this? I can access that x variable and same value in another file.

6
  • 1
    I know its vague, but try window.x = "sachin". Commented Dec 21, 2016 at 5:39
  • use with global variable and order the js file one by one var x = "sachin" is first js file .Then add next js file in below of the file .order is important .<script src="var x=sachin"></script> <script src="2nd file"></script> Commented Dec 21, 2016 at 5:41
  • make sure the file with the variable is before the other file Commented Dec 21, 2016 at 5:41
  • "I can access that x variable and same value in another file." - Are you saying that x in file 1 can't be accessed from file 2 but can be from file 3? In which order do you include the files? Commented Dec 21, 2016 at 5:44
  • 2
    You mean two scripts on the same page or different pages? Commented Dec 21, 2016 at 5:47

4 Answers 4

15

see about local and global variables for more info. http://www.w3schools.com/js/js_scope.asp.

Make sure your var X is not inside a function and that your file is load in the correct order.

<script src="file1.js"><script> //declare var x=1 here
<script src="file2.js"><script> // you can access x from here.
Sign up to request clarification or add additional context in comments.

1 Comment

Basically my project is a simple chat app,which has credentials like API_KEY,like that,does this method works here?
11

A variable in global scope can be access from all javascript file.
Your first js file

  //first.js file
    var globalVariable={
       x: 'sachin'
    };

And your second js file

    //second.js file
    alert(globalVariable.x);

And in html page add-

<script type="text/javascript" src="first.js"></script> 
<script type="text/javascript" src="second.js"></script> 

1 Comment

Can you do it without two script elements? Basically import second.js inside first.js
1

I'm going to assume that you're running JavaScript in the browser. The order in which you include these files matters. If your script tags are in the wrong order, like...

<script src="file2.js"></script>
<script src="file1.js"></script>

If xis defined in file1, you can't use it in file2. file2 loads and runs first.

Comments

1

Two of the simplest ways would be to make the variable global or add it to a particular namespace that both files share.

To make it global (not ideal):

window.x = "sachin";

To add to a common namespace (keep in mind this namespace is global too):

  • Create a namespace in a third file, MYAPP = {};
  • Use namespace in second file: MYAPP.x = "sachin;"
  • Access variable from same namespace in third file: MYAPP.x

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.