Home >>Javascript Tutorial >Javascript Variables
A variable is Simply a container which Contains Some values.
A variable in JavaScript is the name of a storage location.
There are generally two types of variables available in JavaScript:
Variable Declaration Rules: While declaring a JavaScript Variable (also referred as identifiers), there are some rules to follow.
Let's understand the correct and incorrect variables in JavaScript by these following examples:
Correct JavaScript variables
var a = 20; var _str="PHPTPOINT"; var str1="PHPTPOINT";
Incorrect JavaScript variables
var 111=20; var *aa=350;
<script> var a = 5; var b = 10; var c=a+b; document.write(z); </script>
A local variable in Javascript is often declared inside a block or a function and it is accessible within the block and function only.
Let's understand it with these following examples:
<script> function demo() { //local variable var a=5; //We can use only inside this function alert(a); } </script>
A global Variable can be defined as the variable that can be declared outside the function or with window object. A global variable in JavaScript can be accessed from any function.
Let’s understand the global variable with these following examples: Examle 1
<script> //global variable var data=10; function demo() { document.writeln(data); } function demos() { document.writeln(data); } //calling JavaScript function demo(); demos(); </script>
Examle 2
<script> //global variable var data=10; function demo() { alert("Global Variable : "+data); } //calling JavaScript function demo(); </script>
You will have to use a window object in order to declare a global variable inside a function in JavaScript.
Examle
<script> function demo() { //declaring global variable by window object window.value=10; } function demos() { //accessing global variable from other function alert(window.value); } //call function demo(); demos(); </script>
A variable is added in the window object internally, once it is declared outside the function. Now, it can also be accessed through window object.
Let's take an example for this:
<script> var value=10; function demo() { //accessing global variable alert(window.value); } //call demo function demo(); </script>