المعرفة:: JavaScript الحالة::مؤرشفة المراجع:: syahshiimi’s notes, The Complete JavaScript Course 2022 From Zero to Expert
Scope Concepts
What Are Scopes?
Scoping controls how our programs variables are organised and accessed. Simply put, it asks where do the variables live, how we can access it etc.
Lexical Scoping
- Scoping is controlled by placement of functions and blocks in the code.
- The rules of where we can access variables are based on exactly where in the code functions and blocks are written.
Scope
The scope is a space or an environment where the variable is declared.
Scope of a variable
The region of our code where certain variables are accessed.
Types of Scopes
Global
For top level code, where variables are declared outside of any function or blocks. Accessible everywhere.
const name = "A";Function (Local Scope)
Each function creates a scope, where its variable is only accessible within the function.
function square(number) {
const squared = number * number;
return squared;
}
conosle.log(squared); // ReferenceErrorBlock (ES6)
- Variables that are accessible inside the block (if, for, while, etc).
- This only applies to
letandconstvariables. Variables declared withvarend up in the closest function scope. - Functions are block scoped in JavaScript Strict Mode.
if (year >= 1981 && year <= 1996) {
const millenial = true;
}
console.log(millenial); // ReferenceErrorScope Chain
- In general, the parent-child relationship of a scope chain allows variables to be used by the
childelement from theparentelement. - The
parentelement, however, will not have access to thechildscope. - When a variable is not in the current scope, the engine looks up in the scope chain until it finds the variable it’s looking for. This is called variable lookup.
Scope Chain vs Call Stack
Although the scope chain allow us to create the order as to how we can call functions, it has nothing to do with calling the functions itself within the call stack.