JavaScript Tutorial – Scope

JavaScript scope is the set of variables, objects, and functions you have access to. This concept is very important, make sure you funny understand this before moving on to next chapter.

Local JavaScript variable

Local variables are declared within a function and they have local scope. Local scope means these variable can only accessed within the function.

Local variable example

<script type="text/javascript">
   //variable siteName cannot be accessed outside the demoFunction
   function demoFunction() {
      var siteName = "WhatAboutHTML";
      //code here can use siteName
   }
</script>

Local variables are created when the a function starts and deleted when the function is completed.

Global JavaScript variable

All variable declared outside of a function is considered global variables and they have global scope. global scope means these variable can be accessed by all the scripts and functions on the page.

Global variable example

<script type="text/javascript">
   var siteName = "WhatAboutHTML";
   //code here can use siteName

   function demoFunction() {
      //code here can use siteName as well
   }
</script>

JavaScript variables life time

The lifetime of a JavaScript variable starts when it is declared. Local variables are deleted when the function is completed. Global variables are deleted when you close the page.