What is the correct way to define global variables in JavaScript?


A global variable has global scope which means it can be defined anywhere in your JavaScript code.

Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable.

Commonly, a global variable is declared like the following −

<html>
   <body onload = checkscope();>
      <script>
         <!--
         var myVar = "global";   // Declare a global variable
         function checkscope() {
            document.write(myVar);
         }
         //-->
     </script>
   </body>
</html>

But, what you can above is the traditional method of using global variables. The best practice is to use it like the following with “window” −

<html>
   <body onload = checkscope();>
      <script>
         window.myVar = "global";   // Declare a global variable
         function checkscope( ) {
            alert(myVar);
         }
      </script>
   </body>
</html>

Updated on: 13-Jun-2020

347 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements