JavaScript Tutorial || JavaScript Variable
JavaScript Variable
JavaScript variables are containers for storing data values
There are two types of variables in JavaScript : local variable and global variable.
example, x, y, and z, are variables
var x = 5;
var y = 6;
var z = x + y;
x stores the value 8
y stores the value 2
z stores the value 10
1.Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword
2.Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign
3.JavaScript variables are case sensitive, for example b and B are different variables
4.Global Variables − It can be defined anywhere in your JavaScript code.
5.Local Variables − A local variable will be visible only within a function where it is defined.
Global Variables
It is accessible from any function. A variable i.e. declared outside the function or declared with window object is known as global variable. For example
<html>
<body onload = findvalue();>
<script type = "text/javascript">
var xvalue = "global";
</script>
</body>
</html>
Local Variables
local variable will be declared only within a block or function. It is accessible within the function or block only. For example:
<html>
<body onload = findvalue();>
<script type = "text/javascript">
function findvalue( ) {
var xvalue = "local";
document.write(xvalue );
}
</script>
</body>
</html>