Breaking News
yeni film izle hd film seyret film izle

Scope of a variable IN Java Script

Any variable in a function is local to that function & the variables declared outside the function are called a global variables , the local variables can be accessed within the function only, while global variables can be accessed anywhere in the program.
 
Example:
 
<html>

<head>

</head>

<body onclick=”pp()”>

<script>

var global=75

function pp()

{

var local=45

document.write(“<br>This is value of a local variable “+local);

document.write(“<br>This is value of a global variable being accessed inside the function “+global)

}

document.write(“<br>This is value of a global variable “+global)

document.write(“<br> If we tried to print or access local variable’s value here it will generate an error for non declaration of variable “)

document.write(“<br>Click in The white area to view the value of local variable “)

</script>

</body >

</html>

 
Understanding program:
In the above given program we have declared two variables named global and local, global variable is declared outside the function so it is a global variable means could be accessed in the function as well outside the function also, while local variable is declared inside the function pp so it can be accessed within the function in which it is declared , if we tried to access or print it outside the function an error will generate showing the message that the variable is not declared, because the local variable do not have that scope where we are accessing it so it requires a separate declaration.
 
Output is:
This is value of a local variable 45
This is value of a global variable being accessed inside the function 75
Click here to view result of this program on browser
 
Example:
 
<html>

<head>

</head>

<body onclick=”mm()”>

<script type=”text/javascript”>

var global =75

function mm()

{

var local local=45

document.write(“<br>local variable’s Value inside mm function “+local);

document.write(“<br>Global Variable’s Value inside mm function “+global) pp();

}

function pp()

{

local=12 document.write(“<br> local variable’s Value inside pp function “+local);

document.write(“<br>Global Variable’s Value inside pp function”+global)

}

document.write(“<br>Global Variable’s Value outside function “+global)

document.write(“<br><h1 align=center>Click on Me</h1>”);

</script>

</body>

</html>

 
Output is:
local variable’s Value inside mm function 45

Global Variable’s Value inside mm function 75

local variable’s Value inside pp function 12

Check Also

Functions Returning Values In Java Script

Function is a set of statements recognized by a name and can be used as …