Deep JavaScript Foundations, v3

Dynamic Scope

Kyle Simpson

Kyle Simpson

You Don't Know JS
Deep JavaScript Foundations, v3

Check out a free preview of the full Deep JavaScript Foundations, v3 course

The "Dynamic Scope" Lesson is part of the full, Deep JavaScript Foundations, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Kyle demonstrates how dynamic scope works using a theoretical code example.


Transcript from the "Dynamic Scope" Lesson

>> Kyle: What about dynamic scope? I said that it exists in some languages, it does not exist in JavaScript. So this is entirely theoretical. But if this did exist in JavaScript, this is how dynamics code would work. You noticed the function on line 3, the function ask, is making reference to a variable called teacher that does not exist in its own scope.

And we would normally think of it as resolving to that variable because that's how we think lexically. But in a dynamically scoped language, it wouldn't even consult the lexical scope nesting, it would say, hey, where was ask called from. So where was ask called from? It was called from the scope of other class and it would end up resolving teacher to that variable.

>> Kyle: Can you see then that the idea of a dynamic scope is the idea that a function's references to its variables are depended upon where that function was called from? The same function called from 100 different places ends up giving 100 different answers to what the variables are, that may sound like chaos but you should also think of that as sounding like an amazing amount of flexibility and reuse.

Imagine writing one function that could be re-used in all of those different contexts, and these are not right or wrong, by the way. It's not like dynamic scope is bad and evil or weird, it's just so unfamiliar to us because we don't think of it that way. But if you had only ever written dynamic scope and somebody explained lexical scope, they'd say, but how do you like re-use your functions?

[LAUGH] Right? They'd have the same reaction that we might viscerally have to this code snippet. So what we should get from dynamic scope is that it is scope that is determined based upon the conditions at runtime, whereas lexical scope is determined at author time. Even though JavaScript does not have dynamic scope, JavaScript does have a mechanism that gives us this same kind of flexibility, and we'll talk about that later in our course.

So I want you to keep in your mind right now this difference between fixed, predictable, and dynamic, and flexible.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now