I am looking for some guidance on the difference between a global scope variable and a local scope variable. Thanks.
问题:
回答1:
Global variable - declared at the start of the program, their global scope means they can be used in any procedure or subroutine in the program.
Local variable - declared within subroutines or programming blocks, their local scope means they can only be used within the subroutine or program block they were declared in.
Resource: Fundamentals of Programming: Global and Local Variables
Resource: Difference Between Local and Global Variables
回答2:
The difference is where the variable can be accessed or modified. (in the contents of a class for example) A global variable can be accessed or modified anywhere within the class. A local variable, if created in a function within the class, can only be used within that function.
This site provides a nice explanation: https://en.wikibooks.org/wiki/A-level_Computing/AQA/Problem_Solving,_Programming,_Data_Representation_and_Practical_Exercise/Fundamentals_of_Programming/Global_and_Local_Variables
Example from the link above:
1 Module Glocals
2 Dim number1 as integer = 123 // global variable
3
4 Sub Main()
5 console.writeline(number1)
6 printLocalNumber()
7 printGlobalNumber()
8 End Sub
9
10 Sub printLocalNumber
11 Dim number1 as integer = 234 // local variable
12 console.writeline(number1)
13 End Sub
14
15 Sub printGlobalNumber
16 console.writeline(number1)
17 End Sub
18 End Module
Output would be: 123 234 123
回答3:
Global scope variables can use within the program anyware. Global variables are declaring outside any functions. Local scope variable value is only for that particular scope (function).Local variables are declaring inside that particular function.
var fVariable = "Hello World"; //Global Scope Declaration
function printjs() {
var sVariable = "Welcome"; //Local Scope Declaration
console.log(sVariable);
console.log(fVariable);
}
printjs();
console.log(fVariable);
Here you cannot print the value of sVariable outside the function as it is a local variable. But you can print the value of fVariable outside and inside both of the function as it is a global variable