Header Ads

Scope of Variable In JavaScript

When ever we define a variable in javascript , the next question comes what is the scope that variable? Well javascript has two variable types.


  • Global
  • Local
Global:
The variable which is defined outside of any block called global and can be accessed through any part of the page.
Local
The variable which is defined inside of any function or block is called local variable.This can only be accessed through the function or block where it is defined.Javascript uses scope chains to establish the scope for a given function. There is typically one global scope, and each function defined has its own nested scope. Any function defined within another function has a local scope which is linked to the outer function. It's always the position in the source that defines the scope.An element in the scope chain is basically a Map with a pointer to it's parent scope.When resolving a variable, javascript starts at the innermost scope and searches outwards. This is a sample code how to get input from user then store that inside a variable . Now use that variable whenever it is required.


<HTML>
<HEAD>
   <SCRIPT language = JavaScript>
         var name = prompt("Enter your name", "Name");
   </SCRIPT>
</HEAD>


<BODY>
    <SCRIPT language = "JavaScript">
         document.write("<H2> Hello " + name  + "</H2>");
   </SCRIPT>
</BODY>
</HTML>


In this example name is defined as global and accessed through different portion of the page.Now let us understand how it is saved inside the memory. when it is running it takes the input from user and stores that inside of "name" variable. This is outside of any function hence it is placed inside the global scope. Now when we require the "name" it check the scope. It is not inside of any function or block so it then goes for the global scope. If found inside global scope, the reference is established.


Let us take a second example


<html>
<head>
<script type="text/javascript">
function product(a,b)
{
var c=a*b;

return c
}
</script>
</head>

<body>
<script type="text/javascript">
document.write(product(5,4));
</script>

</body>
</html>


here c is defined inside of a function called product so this is a property of the function. All private property of any function is written inside of a structure of that function . This structure is placed inside DOM stack. So again when we are trying to print the output ..Javascript engine checks the location of the variable. It starts from inner most block and found c-the variable is present inside the function block.It prints.




 For further reference: 



Powered by Blogger.