In programming, scope refers to the accessibility of a variable, function or object, the scope determines where you can and cannot access these from. The scope of a certain variable, function or object changes depending on whether it is local or global, or whether it resides within its own code block such as a function or loop.
Local variables vs global variables
A
local
variable is one that can only be accessed within the code block in which it resides, other nested code blocks will also be able to access it. For a variable to be considered local, it must be declared within a code block such as a function or loop using the "var" keyword.
A
global
variable is one that can be accessed from anywhere within an application. For a variable to be considered global, it must be declared outside of any code block such as a function or loop. Alternatively you can also assign a value to a non-declared variable which will automatically create it as a new global variable but this is not advised.
var num1 = 5; // global
num2 = 4; // global
function testFunction(){
var num3 = 9; // local
num4 = 8; // global
// num1 and num2 will still be accessible here as well as num3 and num4
}
// num3 will not be accessible here
console.log( num1 );
console.log( num2 );
console.log( num3 );
console.log( num4 );
Output:
5
4
undefined
8
In the above example we have 4 variables, 3 of which are global and 1 of which is local. The first 2 variables are created outside of a code block, making both of them global no matter what the declaration syntax is. Within the code block, one of the variables is local as the "var" keyword is used to declare it, the other is global as we assign a value to a non-declared variable which will automatically create it as a global variable (avoid doing that).
When we print the values of the variables after the function, the global variables will be accessible but the variable local to the function will not be.
Only declare variables as global if you really need to. Having too many global variables can result in high memory usage, getting confused between variables and assigning a value to the wrong one. Local variables are much cleaner as they are erased from memory after the code block has executed, you can also use the same variable names in different code blocks as long as they don't share the same scope.
function test1(){
var num = 6; // not the same
}
function test2(){
var num = 7; // not the same
}