Global variables are accessible from all other (local) scopes.
The global scope is a scope that contains every variable declared outside of a function (functions create their own scope, known as a local scope, and the variables declared inside functions are known as local variables).
Block statements do not create their own scope when included outside of a function, thus variables declared inside blocks are global (using the const or let keywords changes this).
The following examples explore working with global variables and scopes.
Example 1 – Defining a global variable:
The following declaration takes place outside of a function’s scope, meaning the toys array is a global variable:
const toys = ['Car', 'Airplane', 'Train'];
Example 2 – Defining a local variable:
This example defines the variable toys within the scope of a function, making it a local variable:
function getToys() { const toys = ['Doll', 'Wand', 'Wings']; return toys }
Related Articles:
JavaScript – How to use functions