JavaScript global variable | Example code

Variables don’t have limited scope to use by only a single function and defined outside of functions called global variables in JavaScript.

A global variable can be defined anywhere in your JavaScript code and can be accessed from any function or scripts.

JavaScript global variable Example code

HTML example code:-

<!DOCTYPE html>
<html>
   <body>
      <script>
   
         var myVar = "Global variable";   // Declare a global variable

         function checkscope() {
            document.write(myVar);
         }
         //call function
         checkscope();
   
     </script>
   </body>
</html>

Output:

JavaScript global variable example code

What is the JavaScript global variable window?

To declare JavaScript global variables inside the function, you need to use a window object.

window.variableName

Example code

<!DOCTYPE html>
<html>
<body>
	<script>
		function msg(){  
			window.value="Hello";
		}

		function send(){  
			alert(window.value);
		}
		msg();
		send();
		
	</script>
</body>
</html>

Note: If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable.

Do comment if you have any doubts and suggestion on this basic topic of JavaScript.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.