JavaScript Variables Placement


JavaScript Variables Placement

Based on the place where we declare a variable, the variable can be accessed from all parts of the program or only in certain parts of the program. At the time of a variable be declared without using the var keyword, or we can call an implicit way, then that variable can be accessed from all parts of the program (all functions in the program can call and use these variables), and we call this variable as global variables.
Conversely, if we declare a variable by explicitly JavaScript (declaring variables using the var keyword), then the possibility of accessing these variables depend the location where it is declared :

  • If it is declared at early section of the script program, which means that before the declaration of all functions, all functions in the program can access these variables, and this variable becomes a global variable.
  • If he is declared using the var keyword in a particular function, then the variable that can only be accessed from within the function, and means that these variables are not useful for other functions, and we call these variables into local variables

Let's look at the following example:
<script Language="JavaScript">
<!-
var a = 12;
var b = 4;
function Multiply2 (b) {
var a = b * 2;
return a;
}
document.write ("Two times of ",b, " is",Multiply2(b));
document.write ("The value of a is ", a);
/ / ->
</ SCRIPT>
From the example above, a variable is explicitly declared at the beginning of the script program and also be declared in the function. The following is the result of the above program.
Two times of 4 is 8
The value of a is 12
Here is another example where a variable is implicitly declared within a function:
<script Language="JavaScript">
<! -
var a = 12;
var b = 4;
function Multiply(b) {
a = b * 2;
return a;
}
document.write ("Two times of", b, " is",Multiply2(b));
document.write ("The value of a is ", a);
/ / ->
</ SCRIPT>
Here are the results of the above program.
Two times of 4 is 8
The value of a is 8
From the example above we can see the importance of us getting used to using var word on when creating a new variable.

0 comments:

Post a Comment