Global Variables (example)
<Script>functionSquare (num)/* Pass parameter */{ Total=Num*num; /* Define Global Variables * /returnTotal ; /* return value total*/}var Total= -; /* Define global variables total*/var Number=Square ( -); /* Refer to Square (parameter) to assign to Number*/alert (total); alert (number);</Script>
If Var is not used, the variable is treated as a global variable, and if a global variable with the same name already exists in the script, the function changes the value of that global variable.
Total does not make a var declaration in the square function, so it is a global variable. There is also a total variable declared outside the square function. A global variable is declared outside the function by using the VAR (keyword) + variable name (identifier) method. (one of the global variable declaration methods)
Because a global variable already exists in the script. The total in the square function(num*num assignment to total;num equals number refers to the square (parameter) parameter is 20. So the value will change the value of the external global variable!
Local Variables (example)
<Scripttype= "Text/javascript">functionSquare (num) {var Total=Num*num; /*The multiplication operation is assigned to the local variable total*/ returnTotal ; /*return value to total*/}var Total= -; /*global variable total equals*/var Number=Square ( -);/*refer to square (parameter) to number*/alert (total), alert (number);</Script>
Total in the square function declares a local variable. The total variable is declared outside the function, though. But they are two completely different variables. One is a local variable, and one is a global variable. It's as if the same person has the same name, but in essence they are totally different two people!
Because the square function internally references the external global variable total. So the output value is 50! The number output is 400. Because the global variable has a square (parameter) and is assigned a value. So the num*num multiplication operation inside the square function is assigned to number.
JS Learning Note (ii) Examples of global variables and local variables about functions