JavaScript Variables
- JavaScript uses variables which can be thought of as Named Containers.
- Variables are declared with the 'var' keyword.
- Variable names are case sensitive.
- You can declare multiple variables with the same 'var' keyword.
Example:
var a;
var b;
Example: var a, b;
Variable initialization
Example : Variable initialization
var a = 10;
var b = 20;
Variable Scope
1. Global Variable- Declaring a variable outside the function makes it a Global Variable.
- Variable is accessed everywhere in the document.
Example : Simple Program on Global Variable
<html>
<head>
<script type = "text/javascript">
count = 5; //Global variable
var a = 4; //Global variable
function funccount() // Function Declaration
{
count+=5; // Local variable
a+=4;
document.write("<b>Inside function Global Count: </b>"+count+"<br>");
document.write("<b>Inside function Global A: </b>"+a+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("<b>Outside function Global Count: </b>"+count+"<br>");
document.write("<b>Outside function Global A: </b>"+a+"<br>");
funccount();
</script>
</body>
</html>
Output:
Outside function Global Count: 5
Outside function Global A: 4
Inside function Global Count: 10
Inside function Global A: 8
2. Local Variable
- A variable declared within a function is called as Local Variable.
- It can be accessed only within the function.
Example : Simple Program on Local Variable
<html>
<head>
<script type="text/javascript">
function funccount(a) // Function with Argument
{
var count=5; // Local variable
count+=2;
document.write("<b>Inside Count: </b>"+count+"<br>");
a+=3;
document.write("<b>Inside A: </b>"+a+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
var a=3, count = 0;
funccount(a);
document.write("<b>Outside Count: </b>"+count+"<br>");
document.write("<b>Outside A: </b> "+a+"<br>");
</script>
</body>
</html>
Output:
Inside Count: 7
Inside A: 6
Outside Count: 0
Outside A: 3


