المعرفة:: 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.
Function (Local Scope)
Each function creates a scope, where its variable is only accessible within the function.
Block (ES6)
- Variables that are accessible inside the block (if, for, while, etc).
- This only applies to
let
andconst
variables. Variables declared withvar
end up in the closest function scope. - Functions are block scoped in JavaScript Strict Mode.
Scope Chain
- In general, the parent-child relationship of a scope chain allows variables to be used by the
child
element from theparent
element. - The
parent
element, however, will not have access to thechild
scope. - 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.