In this article, I will guide you on how to Lexical Scoping in Javascript.

So, let's get started,

What is Lexical Scoping?

Lexical scoping in JavaScript means that variables are accessible within the block or function where they are defined, as well as any nested blocks or functions within it. However, they are not directly accessible in outer blocks or functions.

Real-Life Example

Imagine you're on a university campus, and there are multiple buildings with different levels of access. Each building represents a scope, and the rooms inside them represent variables.

JavaScript
function campus() {
   var universityName = "My University"; // Variable in the campus scope

function building() {
  var roomNumber = 205; // Variable in the building scope
  console.log(universityName); // This works, building can access the campus name
}

building(); // Entering the building
console.log(roomNumber); // This will throw an error, campus can't directly access building's rooms

}

campus(); // Entering the campus

Campus

Let's Understand the Above Code

Similar to lexical scoping in JavaScript

This analogy demonstrates how lexical scoping controls the visibility and accessibility of variables based on their location within the nested structure of functions and blocks in JavaScript.