• Javascript

JavaScript Visualized: Scope

by Lydia Hallie

added on June 10, 2024 (6mo ago)

Let's take a look at the following code:

const name = 'Lydia';
const age = 21;
const city = 'San Francisco';
 
function getPersonInfo() {
  const name = 'Sarah';
  const age = 22;
 
  return `${name} is ${age} and lives in ${city}`;
}
 
console.log(getPersonInfo());

We're invoking the getPersonInfo function, which returns a string containing the values of the name, age and city variables: Sarah is 22 and lives in San Francisco. But, the getPersonInfo function doesn't contain a variable named city ๐Ÿคจ? How did it know the value of city?

First, memory space is set up for the different contexts. We have the default global context (window in a browser, global in Node), and a local context for the getPersonInfo function which has been invoked. Each context also has a scope chain.

For the getPersonInfo function, the scope chain looks something like this (don't worry, it doesn't have to make sense just yet):

Alt Text

The scope chain is basically a "chain of references" to objects that contain references to values (and other scopes) that are referencable in that execution context. (โ›“: "Hey, these are all the values you can reference from within this context".) The scope chain gets created when the execution context is created, meaning it's created at runtime!

However, I won't talk about the activation object or the execution contexts in general in this post, let's just focus on scope! In the following examples, the key/value pairs in the execution contexts represent the references that the scope chain has to the variables.

Alt Text

The scope chain of the global execution context has a reference to 3 variables: name with the value Lydia, age with the value 21, and city with the value San Francisco. In the local context, we have a reference to 2 variables: name with the value Sarah, and age with the value 22.

When we try to access the variables in the getPersonInfo function, the engine first checks the local scope chain.

Alt Text

The local scope chain has a reference to name and age! name has the value of Sarah and age has the value of 22. But now, what happens when it tries to access city?

In order to find the value for city the engine "goes down the scope chain". This basically just means that the engine doesn't give up that easily: it works hard for you to see if it can find a value for the variable city in the outer scope that the local scope has a reference to, the global object in this case.

Alt Text

In the global context, we declared the variable city with the value of San Francisco, thus has a reference to the variable city. Now that we have a value for the variable, the function getPersonInfo can return the string Sarah is 22 and lives in San Francisco ๐ŸŽ‰