How to declare global Variables in JavaScript?

JavascriptWeb DevelopmentFront End Technology

A global variable has global scope. The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.

  • Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
  • Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

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.
Here’s how you can declare a global variable −

<html>
   <body onload = checkscope();>
      <script>
         <!--
            var myVar = "global"; // Declare a global variable
            function checkscope( ) {
               var myVar = "local"; // Declare a local variable
               document.write(myVar);
            }
           //-->
      </script>
   </body>
</html>
raja
Ali
Published on 10-Jan-2018 16:54:14
Advertisements