JavaScript Variable Scope

A scope of a variable is the region of the program where it is visible. Where being visible means that the variable has been declared and is available for use. Scope can be specified where you have to access variables (functions or objects). This way you will be able to manage your code efficiently. In JavaScript there are two types of scope :

1. Local scope
2. Global scope

1. Local Scope :

A variable that is visible only in a specific context - for example a function, has a local scope. A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

2. Global Variable :

A variable that is visible everywhere in the program has global scope.  A global variable has global scope which means it can be defined anywhere in your JavaScript code.

A context is the set of defined data that make up the execution environment. 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. Below is the example of variables with local and global scope.
<html>
<head>
  <title>Javascipt Scope</title>
</head>
<body>
  <script type="text/javascript">
    var myvar = "Global Scope";
    function localscope() {
      var myvar = "Local Scope";
      document.write(myvar);
    }
    
    localscope();
    document.write(myvar);
  </script>
</body>
</html>
Output :

Local Scope
Global Scope


Next Topic :