Demystifying Lexical Scope in JavaScript

hey there ๐ i'm Samia, a Backend developer turning to frontend world. i used to work as a Laravel and PHP developer for 3 and half years, in that journey, i had to deal from time to time with some frontend tasks, like fixing responsiveness or converting some psd files into HTML & CSS, that was when i fall in love with it.
I loved the idea of turning creative and beautiful design into reality, so i made that career switch and now turning fully to Frontend development.
Feel free to checkout my journey on Instagram or just pass Hi
Scope is a fancy word for what data is available to me at any line of code
Lexical scope, in simple terms, is all about where you declare your functions. This choice determines which data a function can access when it's executed
To illustrate this concept, consider the following example:
// global scope
function outer() {
const outerMessage = "Hello from outer!";
function inner() {
const innerMessage = "Hello from inner!";
console.log(`${innerMessage} and ${outerMessage}`);
}
return inner;
}
const myFunc = outer();
myFunc(); // Outputs: "Hello from inner! and Hello from outer!"
In this case, innerMessage is accessible to the inner() function because it's scoped within its parent function.
Note that outerMessage is also accessible because it resides in the parent scope of inner(), here is how this is possible
JavaScript initially looks for a variable in the current scope (
inner()in this case).If the variable is not found there, it continues the search in the parent scope (
outer()in this case).If it's still not found, JavaScript keeps climbing the scope chain until it reaches the global scope.
If the variable is not found in the global scope, it returns a reference error, indicating that the variable is not defined.
This process of traversing up to the global scope is known as Scope Chaining.
Understanding Lexical Scope and Scope Chaining is crucial for writing effective JavaScript code. It empowers you to control the accessibility of variables in your functions.
Happy coding! ๐๐ฉโ๐ป๐จโ๐ป
#JavaScript #LexicalScope #ScopeChaining #WebDevelopment #Programming #CodingDemystified



