Scope in a programming language controls the visibility and lifetime of variables and parameters.
Another way of thinking about scope: The part of the program where a particular identifier is visible or accessible such as a variable or function name.
Why am I ranting about scope, well..., it's because of the following reasons:
Security. Variables can only be accessed from a certain area of the program.
Reduces naming collision. We can use the same variable name in different scopes.
Bugs. We all love bugs or do we? Getting to know a little bit more about scope will help you understand variable values or issues.
Before I get in to examples, we have to know what types of scope exist:
- Global
- Function
- Block
Global
Any variable that is not inside a function or block ( a pair of curly braces ) is inside the global scope.
Function
Any variable that is declared inside a function can only be accessed within that function, that means you cannot access them from outside it.
Block
ES6 introduced let and const variables, unlike var, they can be scoped to the nearest pair of curly braces. That means they can't be accessed outside that pair.
Finally, how does JavaScript find the variable value.
- Check current scope
- Check outer scope
- Check global scope
If it's still not able to find the variable, it will either implicitly declare the variable in the global scope or return an error.
Time for examples:
Global
var meow = 'Meow';
function cat () {
return meow
}
// value returned by cat is 'Meow'
cat()
console.log(meow) // Prints 'Meow'
In this case, the variable meow will not return an error since it is in the global scope and is accessible everywhere since it is not function scoped or block scoped.
Function
function cat () {
var meow = 'Meow';
return meow
}
// value returned by cat is 'Meow'
cat()
console.log(meow) // Uncaught ReferenceError: meow is not defined
If we try to access meow outside of cat it will return a Uncaught ReferenceError: meow is not defined
since meow is only accessible or visible in the function cat.
Block
if(true) {
const cat = 'meow';
var meow = 'Meowwwww!!!!';
console.log(cat); // Prints 'meow'
}
console.log(cat); // Uncaught ReferenceError: cat is not defined
console.log(meow); // Prints 'Meowwwww!!!!'
So, what is going on here, the variable cat is bound to the if statement because of the curly braces or block scope.
In this case the variable cat if accessed outside the if statement will return an error as defined above but since meow is not block scoped it will return the expected value. Remember const and let variables are block scoped.
Summary
- A scope is an area where a variable is visible and accessible.
- Just like functions, scopes in JavaScript can be nested and the JavaScript engine traverses the scope chain ( how JavaScript looks for the variable ) to find the variables used in the program.
Top comments (1)
Thanks Niki, I'm pretty new at this!