0

Suppose I have some html file and it's have some script inside it. Then, I need to use another one script and want to use some variable from previous one. How Can I do it? Example:

<body>
 <script>
 var a = 1;
 </script>
 <p id="p"></p>
 <script>
 document.getElementById("p").innerHTML = a;
 </script>
</body>

Its says that "a" is undefined.

asked Jul 26, 2014 at 8:58
4
  • 1
    It is working fine do you have variable in different JS files Commented Jul 26, 2014 at 9:00
  • 2
    As posted your code works OK. See jsfiddle.net/E6cup Commented Jul 26, 2014 at 9:00
  • 1
    It works without an error. Keep in mind that order of the script tag matters. Commented Jul 26, 2014 at 9:07
  • @Dima better tell also what was the problem. Commented Jul 26, 2014 at 9:12

2 Answers 2

2

Yes, you can do it. Your code works without any error. If you declare a variable inside the script tag directly, it comes under global scope which can be accessible from anywhere. But that script must be included before script which uses the variables.

Better you can define your namespace and use that. Otherwise your global variable most likely clash with other script's variable. It will be painful to debug.

 var myNamespace = {};
 myNamespace.a = 2;

In other scripts, use it like myNamespace.a.

answered Jul 26, 2014 at 9:02
Sign up to request clarification or add additional context in comments.

Comments

0

Just Put all Script codes inside a Head tag

<head>
 <script>
 var a = 1;
 </script>
 <script>
 document.getElementById("p").innerHTML = a;
 </script>
</head> 
<body>
 <p id="p"></p>
</body>
answered Jul 26, 2014 at 9:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.