Scope - scope of variables¶
Scope is the "visibility" of a variable. It determines where we will have access to the variable. In JavaScript, variables can have a scope that is:
- global
- local
Global variables¶
Variables declared at the highest "level" of the programme 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 a global variable because it is global in scope
}
printGlobalVariable(); // the 'global const variable' will appear on the screen
Local variables¶
Variables declared using 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 in 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 from those declared with let
and const
. Such a variable can be accessed within the entire function, even if it is declared in an internal code block, within a function, for example:
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); // 10 will be displayed on the screen
}
functionScopeExample();
console.log(funVariable); // we get an error: Uncaught ReferenceError: funVariable is not defined
The variable foo
can be displayed despite the fact that it is declared inside the conditional statement block because we have access to it within the entire function, since it was declared using the keyword var
.