Introduction to Scope of Variable In JavaScript
Whenever we define a variable in javascript, the next question comes what is the scope of that variable? Well, javascript has two variable types.
- Global
- Local
Global:
Local:
<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, the name is defined as global and accessed through different portions of the page. Now let us understand how it is saved inside the memory.
when it is running it takes the input from the user and stores that inside of the “name” variable. This is outside of any function hence it is placed inside the global scope.
Further visit: Best Tip to Use 4 Methods in Button in JavaScript
Now when we require the “name” it checks the scope. It is not inside of any function or block so it then goes for the global scope. If found inside the global scope, the reference is established.
Let us take a second example
<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 the DOM stack. So again when we are trying to print the output .. the Javascript engine checks the location of the variable. It starts from the innermost block and found c-the variable is present inside the function block. It prints.
For further reference:
- http://stackoverflow.com/questions/500431/javascript-variable-scope
- http://www.mredkj.com/tutorials/reference_js_intro_ex.html