Skip to content

JavaScript global variable | Example code

  • by

A global variable in JavaScript is a variable that is declared outside of any function and can be accessed from any part of the code within the same context, such as a web browser or Node.js environment.

Or you can say, variables don’t have limited scope to use by only a single function and are defined outside of functions. A global variable can be defined anywhere in your JavaScript code and can be accessed from any function or script.

It’s recommended to use local variables and functions within specific scopes whenever possible, to keep your code organized and reduce the risk of naming conflicts.

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. It represents the current browser window or the global scope in a web browser environment.

It is created automatically when a script is loaded on a web page and contains many properties and methods that can be used to interact with the current browsing context.

window.variableName

Example code

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

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

When in doubt, it’s often better to use local variables and functions within specific scopes to keep your code organized and minimize the risk of errors.

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 or suggestions 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading