Javascript Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this:

var name;
There are two types of variables:
  1. Local Variable
  2. Global Variable
Local Variable- It is declared inside block or function. Example
<script>  
functionabc(){  
var x=10; //local variable  
</script>
Global Variable-It has global scope which means, it can be defined anywhere in JavaScript code. A variable is declared outside the function. Example
<!DOCTYPE html>  
<html>  
<body>  
<script>  
var data =200; //global variable  
function a(){  
document.writeln(data);  
}  
function b(){  
document.writeln(data);  
}  
a();//calling javascript function  
b();  
</script>  
</body>  
</html>
Try Now Declaring JavaScript global variable within function To declare JavaScript global variable inside function, we need to use window object. Example
window.value=90;
Now it can be declared inside any function and can be accessed from any function. Example
<!DOCTYPE html>  
<html>  
<body>  
<script>  
function a(){  
window.value=50; //declare global variable by use of window object  
}  
function b(){  
alert(window.value);//access global variable from other function  
}  
a();  
b();      
</script>  
</body>  
</html>
Try Now



ADVERTISEMENT
ADVERTISEMENT