12 April 2016
There are two types of variable scope in javascript: global scope and local scope.
Global scope applies to variables that have been declared outside of any function. They can be accessed by any block of code. For example var name = “Oliver”;
would be declared as global, if it appears outside of a function block.
Local scope applies to variables that have been declared inside a function block of code, i.e. in their neighbourhood. Variables with local scope can be accessed by functions or blocks of code in the same scope or neighbourhood, but not others. For example, I can play basketball in the east side of town, but I’m forbidden to play in the west.
Javascript remembers what local variables can be accessed by which code, by giving it a ‘closure’ reference. A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.
Variables, whether local or global, are declared first, as if they were at the top of a page or script. Javascript processes all variables before executing other code. This is true even if the variable is declared inside a conditional statement, or a function block of code. Variables are all initially given values of ‘undefined’, until they are called. When they are called, they take on the values assigned to them, but not before.
Interestingly, variables inside function code blocks can be made global, by declaring them without a ‘var’: name = “Oliver”;
. This variable would be accessed as if it was global, even though it has been declared inside a function which would usually have local scope.
Also, the use of ‘let’, allows for scope to be temporarily changed within the block it is called. For example, say a global variable is defined var name = “Oliver”;
. Then in another block of code, we write let name = “Aidan”;
, the name
variable will be defined as Aidan
in that block, instead of Oliver
. Think of the use of ‘let’ as a temporary amnesia on the previous variable declaration.