Scope of Variable In JavaScript: Quick Facts in 2021

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:

The variable 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 the 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 that 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 the 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, 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.

READ  Exclusive Facts on Javascript Interpretation in the URL box in 2021

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

<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 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:

Share and Enjoy !

Leave a Reply

Your email address will not be published. Required fields are marked *