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.
There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.
We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.
The variable number is declared globally and may be accessed from other file when including its declaration with the “ extern ” prefix. However, the variable coefficient is only accessible from the file in which it is declared and only from that point on (it is not visible in function main .
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>
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.
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 x
is defined in file1, you can't use it in file2. file2 loads and runs first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With