Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
Global scope
The local scope is limited by the function, so we cannot directly access local variables from outside of it. However, a function can access variables declared in an enclosing scope.
If we access some non-local variable from inside the function, JavaScript will move one level higher and search outside the scope of the function to find the desired variable. It is a known principle that variable names are looked up in the current scope and then in enclosing scopes.
var food = 'salad';
var eatDinner = function () {
// This function does not declare any local variables.
console.log('I ate ' + food);
};
eatDinner();
// The function reads the food variable,
// which is declared outside of eatDinner
// Outputs: I ate salad.
In our example, the food variable is not declared inside a particular function. It is declared at the level of the entire program, which means that functions can access it unless a closer scope declares the same name. In other words, it can be used inside a function with no closer variable of the same name. These variables, which are declared at the very top level, outside of all particular functions, are called global. And the scope in which they can be found is called the global scope. We can tell from their name that the variables from this scope can be seen throughout the entire program code, unless a closer scope declares a variable with the same name.
If a variable is accessed from inside a function, but this variable has not been declared in any accessible scope, the console will output an error.
- script.js
Thanks! We’ll fix everything at once!
Comments