Member-only story

Lexical and Dynamic Scope Usage

Do you keep forgetting the difference between lexical and dynamic scoping? Perhaps it helps to think about when you would pick one over the other.

Erik Engheim
5 min readNov 25, 2020
A rifle scope which has absolutely nothing to do with scopes in programming languages ;-) But it looks really cool.

In programming languages we frequently talk about whether variables have lexical or dynamic scope.

However for some reason lexical and dynamic scope is one of those things I keep having to look up, because I always forget it. I am sure I am not alone, so this is an attempt at coming up with examples and associations which will help you remember.

We could look up the dictionary definition of Lexical:

of or relating to the words or vocabulary of a language, especially as distinguished from its grammatical and syntactical aspects.

It may give a clue that lexical scoping is about determining scope based on body of text itself. The code as you read it. It you do not have to consider how the code is executed or how the state of your environment changes over time.

That is why we tend to prefer lexical scoping. You can simply examine the code to figure out where the value of a variable comes from. So other possible ways to help you remember…

--

--

Erik Engheim
Erik Engheim

Written by Erik Engheim

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.

No responses yet