What Is Lexical Scoping?

TechDogs Avatar

Lexical scoping is a fancy saying, "A variable's scope is determined by its location in the code". It makes it so that when you type in the word 'cosmos' in a sentence, your computer doesn't think you're referring to the guy who runs a dive bar in Brooklyn. It works like this: Lexical scoping determines where a variable can be accessed within your program. A variable's scope is determined at compile time and cannot be changed after that point. Lexical scoping refers to the fact that variables can only be accessed within their scope. In other words, they can only be referenced by code blocks that are physically inside theirs. The practise of lexical scoping is a method that can be utilized to make a program easier to read. It involves hiding the implementation details of each function so that they are no longer visible outside of the process they were written inside. This makes programs more readable because it allows you to focus on what the code does rather than how it does it. It also makes it easier for other programmers to read and understand your code since they don't have to worry about what is happening behind the scenes when they call a function. Lexical scoping is a simple concept: variables are only accessible within their declared region. So, if you declare a variable in a function, it can only be accessed by that function, not outside of it. That's why lexical scoping gives rise to lexical closures. Because you can't access variables outside their declared scope, you have to make an anonymous function (aka "closure") to wrap around them and access them inside the function where they were declared. But lexical scoping also ensures that parts will still be re-entrant.

TechDogs Logo

Join Our Newsletter

Get weekly news, engaging articles, and career tips-all free!

By subscribing to our newsletter, you're cool with our terms and conditions and agree to our Privacy Policy.

  • Dark
  • Light