# 🔍 Demystifying  JavaScript Lexical Scope

Hey fellow coders! 🚀 Let's talk about something cool in the JavaScript world – lexical scope! 🤓

So, what's the deal with lexical scope, you ask? Well, buckle up because it's a concept that can make your coding life a whole lot easier.

# What is the lexical scope? 🤔

In plain English, the lexical scope is like the GPS of your variables in JavaScript. It figures out where a variable belongs based on where it's hanging out in your code. It's all about location, location, location 📍!

Imagine this: you've got a bunch of variables and functions doing their thing in your code. Lexical Scope steps in and says, "Hey, I know where you belong, buddy!". It does this magic during code compilation, not when the code is running. That's right – it's like having a superhero organize your variables before the action begins.

Let’s check out some examples 🛒!

# **Global Scope 🌎 vs. Local Scope 📍**

In the following example, `globalVar` is accessible inside and outside the function `showScope` because it's declared in the global scope. However, `localVar` is only accessible within the `showScope` function because it's declared in the local scope.

```jsx
// Global variable 🌎
let globalVar = "I'm global!";

function showScope() {
  // Local variable 📍
  let localVar = "I'm local!";

  console.log(globalVar); // Accessing global variable 🌎
  console.log(localVar);  // Accessing local variable 📍
}

showScope();  // Output: "I'm global!" and "I'm local!"

console.log(globalVar); // ✅ Output: "I'm global!"
console.log(localVar);  // ❌ ReferenceError: localVar is not defined
```

# **Nested Lexical Scope 🪆**

In this example, `innerFunction` has access to both its own local variable `innerVar` and the variable `outerVar` declared in the outer function `outerFunction`. However, these variables are not accessible outside their respective scopes.

```jsx
function outerFunction() {
  let outerVar = "I'm from outer!";

  function innerFunction() {
    let innerVar = "I'm from inner!";
    console.log(outerVar); // Accessing outer variable
    console.log(innerVar); // Accessing inner variable
  }

  innerFunction();
}

outerFunction();  // Output: "I'm from outer!" and "I'm from inner!"

console.log(outerVar); // ❌ ReferenceError: outerVar is not defined
console.log(innerVar); // ❌ReferenceError: innerVar is not defined

```

# Final thoughts 💭

Understanding lexical scope is crucial for writing clean and organized code in JavaScript. It's like knowing the neighborhood of your variables and functions, making your code more predictable and easier to debug. Happy coding! 🚀🔍

# References ※

%[https://developer.mozilla.org/en-US/docs/Glossary/Scope]
