-3

how can we declare a variable globally so that we can use it in different different scripts written within same page.In below code how can i declare variable globally in script 1 so that i can used it in script 2.

.php page

 <!DOCTYPE HTML>
 <html>
  <head>
  <script type="text/javascript">
   //this is first script//
   </script >
  <script type="text/javascript">
   //this is second script//
   </script >
  </head>
 </html>
Archana Gupta
  • 73
  • 2
  • 9

2 Answers2

1

You need to properly closing the script tag .and declare the var in first one then access with below script .

Order of the script is more important.

if you add some other js link to handle var a.add this new link below the first one

Updated

1.defined variable validation and replace the global varibale

<!DOCTYPE HTML>
 <html>
  <head>
  <script type="text/javascript">
   //this is first script//
   var a ="hi"
   </script>
  <script type="text/javascript">
   //this is second script//
   if(typeof a !== "undefined") { // for defined varibale validation
   console.log(a)
   a='hello' // replaced
   console.log(a)
   }
   </script>
  </head>
 </html>
prasanth
  • 22,145
  • 4
  • 29
  • 53
0

i suggest you to create one file for global variable like 1st glob.js

and Code like

<script type="text/javascript">
   //this is GLOBAL script//
   var a ="MY_FRIST_VAR"
   </script>

and used it as

<script type="text/javascript" src="glob.js"></script>
 <script>
console.log(a)
<script>