logo
JavaScript scopes
In JavaScript scope defines accessibility of variables, objects and functions.

There are two types of scope in JavaScript.
1. Global scope
2. Local scope
Global Scope :
Global Scope is nothing but a window level scope. Here, Global variable present throughout the application
Example :
<html>
<head>
<title>Javascript Global Variables</title>
</head>
<body>
 
<h4 id="web_site"></h4>
 
<script type="text/javascript">

  var website = "www.freetimelearning.com";
  myFunction();
  function myFunction() {
  document.getElementById("web_site").innerHTML =
  "This is our website : " + website;
  }

</script>
      
</body>
</html>
Output :

This is our website : www.freetimelearning.com

Local Scope :
Variables declared within a JavaScript function, become LOCAL to the function. Local variables cannot be accessed or modified outside the function declaration.
Example :
<html>
<head>
<title>Javascript Local Variables</title>
</head>
<body>
 
<h4 id="local_scope"></h4>
 
<script type="text/javascript">

myFunction();
document.getElementById("local_scope").innerHTML =
"Our website is " + typeof website;
 
function myFunction() {
    var website = "www.freetimelearning.com";
}

</script>
 
</body>
</html>
Output :

Our website is undefined