Scope - range of variables¶
Scope determines the "visibility" of a specific variable. This visibility determines whether we will have access to the variable in a given place in the code. In JavaScript, variables can have a scope:
- global
- local.
Global variables¶
Variables declared at the top "level" of the program are called global variables. This means that we can access them from anywhere else in the program. However, we should not abuse this possibility and try to use separate objects and functions. The following example shows how to use global variables.
const globalVariable = "global const variable";
function printGlobalVariable() {
console.log(globalVariable); // you can display the global variable because it is of global scope
}
printGlobalVariable(); // the following will be displayed 'global const variable'
Local variables¶
Variables declared with the keywords let
and const
are only visible in the code block in which they are declared (inside {}
), e.g .:
function scopeDemonstration() {
const value = 7;
let hello = 'Welcome to SDA';
console.log(`Value id ${value}`);
if (value % 2 === 1) {
console.log(`Value ${value} is odd`);
}
if (hello.length > 3) {
console.log(`string \'${hello}\' has length greater than 3`);
}
}
Variables declared with var
behave slightly differently than those with let
and const
. We have access to such a variable within the entire function, even if it has been declared in an internal code block, inside the function, i.e .:
function functionScopeExample() {
var funVariable = "Hello I am declared with var keyword";
console.log(funVariable);
function childFunction() {
console.log(funVariable); //
}
childFunction();
if (1 === 1) { // I will always go inside this if
var iWillBeVisibleOutsideThisBlock = 10;
}
console.log(iWillBeVisibleOutsideThisBlock); // and the screen will display 10
}
functionScopeExample();
console.log(funVariable); // we will have an error here: Uncaught ReferenceError: funVariable is not defined
We can display the foo
variable despite the fact that it is declared inside a conditional statement block, because we have access to it throughout the entire function, because it was declared using the var
keyword.