Understanding scope in JavaScript

garrettlove8

Garrett Love

Posted on August 17, 2024

Understanding scope in JavaScript

This topic has been covered many times over, nevertheless, I’d like to talk about what scope is (using JavaScript) from the perspective of the problem it is intended to address.

What problem does scope actually solve?

As applications increase in size, they also increase in complexity - scope is a tool for managing such complexity.

Coupling vs. decoupling

Let’s pretend that we have a global variable radius which is set to 7 and a function createSpecialButton() which returns a “special” button:

let radius = 7;

function createSpecialButton(radius) {
  return <button radius={radius}>Click Me!</button>
}

const button = createSpecialButton(radius);
Enter fullscreen mode Exit fullscreen mode

This function returns a button with a specific radius, which in this case is set to 7. Right now, there is no problem with the code, as we know what the radius is set to and therefore know what the resulting button will look like. However, what happens what we add in two more functions which both depend on the radius variable? Our code now looks like this:

let radius = 7;

function createSpecialButton() {
  return <button radius={radius}>Click Me!</button>
}

function profileButton() {
  radius = 10;
  return <button radius={radius}>Click Me!</button>
}

function registrationButton() {
  radius = 16;
  return <button radius={radius}>Click Me!</button>
}

const profileButton = profileButton();
const registrationButton = registrationButton();
const button = createSpecialButton();
Enter fullscreen mode Exit fullscreen mode

After making this change, what will the value of radius be when calling createSpecialButton()? If you guessed 16 , you’d be right.

Just by adding two additional functions, we’ve greatly increased the complexity of our code, and now live in a world in which multiple, unrelated, pieces of code are relying on the same dependency. Now, imagine this was a much larger full-stack application - it would quickly become difficult to reason about where certain pieces of state were coming from and how to fix bugs when they come up.

To fix this, we can define separate radius variables for each function:

function createSpecialButton() {
  const radius = 7;
  return <button radius={radius}>Click Me!</button>
}

function profileButton() {
  const radius = 10;
  return <button radius={radius}>Click Me!</button>
}

function registrationButton() {
  const radius = 16;
  return <button radius={radius}>Click Me!</button>
}

const profileButton = profileButton();
const registrationButton = registrationButton();
const button = createSpecialButton();
Enter fullscreen mode Exit fullscreen mode

You might look at this change and say “well, ok, but now there is more code - that doesn’t seem right”. That’s correct, there is more code, however less code isn’t better if it results in less maintainable code - the change we made improves our code’s maintainability, and that is always a good thing.

Types of scope in JavaScript

Global Scope

Global scope is accessible by everything across you entire application. If you’re writing a Node.JS app you probably won’t work with or encounter global scope. However, if you’re working in a web app, you could put declarations in global scope by using a script tag or using window.SOMETHING.

For example, using the script tag, you might do something like this:

<script>
  let username = "Garrett";
</script>
Enter fullscreen mode Exit fullscreen mode

Also, MDN phrases their definition of “global scope” as “The default scope for all code running in script mode.” I think the above example is what they’re referring to.

While using the window global object, you might do something like this:

  window.username = "Garrett";
Enter fullscreen mode Exit fullscreen mode

Module Scope

If you’re working in a Node.JS project, module scope is what you’ll be working with at the highest level. Each file with a .js (or .ts) extension is a separate module, meaning at most your declarations will be accessible by everything in a given file, unless you explicitly export them.

For example, in user.ts, both functions can access the variable name.

// user.ts

const name = "Garrett";

function greet() {
  console.log("Hello, ", name)
}

function greetAgain() {
  console.log("Hello again, ", name)
}
Enter fullscreen mode Exit fullscreen mode

However, in this version of user.ts, only accessName() can access the variable name:

// user.ts

function greet() {
  const name = "Garrett";
  console.log("Hello, ", name)
}

function greetAgain() {
  console.log("Hello again, ", name)
}
Enter fullscreen mode Exit fullscreen mode

Note that in both of these modules, nothing is exported. In other words, code in other modules has no way of knowing about this code and thus cannot import and use it. We can change that though:

// user.ts

export function greet(name: string) {
  console.log("Hello, ", name)
}
Enter fullscreen mode Exit fullscreen mode

Now, both functions are exported, and can thus be used by other modules. This is technically different than the concept of global scope we talked about early, but it’s similar in that we’re making code available to the entire application by way of importing it from one module to another.

Function Scope

We’ve actually already seen function scope. Check out the code below (it’s the same code from one of the snippets above):

// user.ts

function greet() {
  const name = "Garrett";
  console.log("Hello, ", name)
}

function greetAgain() {
  console.log("Hello again, ", name)
}
Enter fullscreen mode Exit fullscreen mode

Try running this - greetAgain() will run into an error because the name variable it’s trying to read only exists within the context (i.e. “scope”) of greet().

Note: you might see this referred to as “local scope”.

Block Scope

Block scope is an interesting one because it only works with newer variable types - specifically, let and const, not var. Let’s take a look.

{
  let firstName = "Garrett";
  const lastName = "Love";
  var fullName = "Garrett Love";
  // firstName and lastName CAN be accessed here
  // fullName CAN be accessed here
}

// firstName and lastName CANNOT be accessed here
// fullName CAN STILL be accessed here
Enter fullscreen mode Exit fullscreen mode

In the above example, we can see that 1) Placing code within a {} creates a code block. 2) The variables defined using let and const can only be accessed within that code block. 3) The variable created with var doesn’t follow the rules of block scope, as it can still be accessed outside the {}.

Note: Modern JavaScript uses let and const for variable declarations and not of var.

Declarations should be made within the smallest necessary scope

In closing, remember that scope is a tool for managing complexity in our code, and the higher up in the level of scope you put declarations, the more complexity there will be in your code, so it’s best to aim for declarations to be placed in the smallest scope necessary.

💖 💪 🙅 🚩
garrettlove8
Garrett Love

Posted on August 17, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Understanding scope in JavaScript
javascript Understanding scope in JavaScript

August 17, 2024