JavaScript Scope Explained: Everything You Need to Know

Megan Tipps
6 min readJun 23, 2023

--

Have you ever wondered how JavaScript keeps track of variables and functions in different parts of your code? Scopes are like special rules that determine where your code can access and use these essential building blocks. Just like organising your toys in different rooms of your house, understanding scopes in JavaScript helps keep your code neat and organised and prevents any confusion or conflicts.

Global Scope

When we talk about the global scope, it means that something (like a variable or a function) can be used anywhere in our code. It’s like having a special box that holds all our stuff; we can access it from any room in our house.

For example, let’s imagine we have a game where we must keep track of different animals in a zoo.

let animalCount = 0;

function addAnimal() {
animalCount++;
}

function displayAnimalCount() {
console.log("Total number of animals: " + animalCount);
}

addAnimal(); // Increase animalCount by 1
displayAnimalCount(); // Output: Total number of animals: 1

Our global scope has a special counter called animalCountthat starts at 0. This counter keeps track of how many animals we have in our game.

Now, imagine we have two special buttons in our game. One button adds a new animal, and the other shows how many animals we have. Both buttons can access and use the animalCount variable because it’s in the global scope.

So, when we click the add animal button, which increases the animalCount by 1. And when we click the show count button, it displays the current value of animalCount to tell us how many animals we have.

The global scope is helpful because it allows us to use variables and functions from anywhere in our code. But we need to be careful not to accidentally change or mess up these global variables when we don’t mean to. It’s like sharing a toy with everyone in the house — we must ensure we don’t break it or take it away from others who want to play with it.

Local Scope

Local scope means that something (like a variable or a function) can only be used within a specific part of our code, like inside a function or a set of curly braces `{}`. It’s like having a toy you can only play with in your room and not anywhere else in the house.

Using the same game where we will count animals in different areas of the zoo:

function countAnimals() {
const areaAnimalCount = 10;
console.log("Total animals in this area: " + areaAnimalCount);
}
countAnimals(); // Output: Total animals in this area: 10
console.log(areaAnimalCount); // Error: areaAnimalCount is not defined

We create a unique function countAnimals() that tells us how many animals are in a specific area. Inside this function, we have a special counter areaAnimalCount that keeps track of the animals in that area.

When we run the countAnimals() function, it calculates and shows the number of animals in that specific area, which might be 10. But if we try to use the areaAnimalCount counter outside of the function, we’ll get an error because it’s only meant to be used inside the function.

So, the areaAnimalCount variable is like a special toy that only works inside the countAnimals() function. We can’t use it outside of that function because it’s not meant to be used there.

Local scope is helpful because it allows us to create variables and functions specific to certain parts of our code.

Function Scope

Function scope means that variables and functions created inside a function are only accessible within that function. It’s like having a secret room in your house where you can keep your toys, and only you can access them when you’re inside that room. The function scope is very similar to the local scope and will have many of the same logic.

Let’s continue with our animal-themed example. Imagine we have a function called countAnimals() that counts the number of animals in a specific area of the zoo. Inside this function, we can create a variable called areaAnimalCount to keep track of the number of animals.

function countAnimals() {
const areaAnimalCount = 10;
console.log("Total animals in this area: " + areaAnimalCount);
}
countAnimals(); // Output: Total animals in this area: 10
console.log(areaAnimalCount); // Error: areaAnimalCount is not defined

In this example, the countAnimals() function has its particular room, known as the function scope. Inside this function scope, we have a variable called areaAnimalCount that holds the number of animals in that specific area.

When we run the countAnimals() function, it tells us the total number of animals in that area, which is 10 in this case. However, if we try to access the areaAnimalCount variable outside the function, we’ll get an error because it only exists within its secret room.

Think of it as having a hidden box of toys you can only play with inside your secret room. You can’t access those toys from the living room or outside because they belong to that special room.

The concept of function scope is helpful because it allows us to create variables and functions that are specific to a particular function.

Block Scope

Block scope means that variables and functions created inside a set of curly braces `{}` (also known as a block) are only accessible within that block. It’s like having a secret treasure chest that can only be opened and used inside a specific room of your house.

Let’s continue with our animal-themed example. Imagine we have a code block that represents a specific area in the zoo enclosed within curly braces. Inside this block, we can create a variable called areaAnimalCount to keep track of the number of animals in that area.

{
const areaAnimalCount = 10;
console.log("Total animals in this area: " + areaAnimalCount);
}
console.log(areaAnimalCount); // Error: areaAnimalCount is not defined

In this example, the code block represents a particular zoo area. Inside this block, we have a variable called areaAnimalCount that holds the number of animals in that specific area.

When we run the code, it tells us the total number of animals in that area, which is 10. However, if we try to access the areaAnimalCount variable from outside the block, we’ll get an error because it only exists within its secret treasure chest.

Think of it like finding a hidden treasure chest full of toys inside a specific room. You can only play with those toys while you’re inside that room, and you can’t take them out to the other rooms of your house.

Block scope is helpful because it allows us to create variables limited to a specific block of code, such as a loop or an if statement.

Lexical Scope

In JavaScript, lexical scope means that variables and functions are accessible within their own code blocks and any nested code blocks inside them. It’s like having a set of nesting dolls, where each doll knows about the dolls inside, but the inner dolls are unaware of the dolls outside.

Let’s continue with our animal-themed example. Imagine we have a function called countAnimals() that counts the number of animals in a specific area of the zoo.

function countAnimals() {
const areaAnimalCount = 10;

{
const subsectionAnimalCount = 5;
console.log("Total animals in this subsection: " + subsectionAnimalCount);
console.log("Total animals in this area: " + areaAnimalCount);
}

// We can access the areaAnimalCount here
console.log("Total animals in this area: " + areaAnimalCount);

// We can't access the subsectionAnimalCount here
console.log(subsectionAnimalCount); // Error: subsectionAnimalCount is not defined
}
countAnimals();

In this example, the countAnimals() function has its own code block, and inside that block, we have another nested code block representing a subsection of the zoo area. Within the nested code block, we define a variable called subsectionAnimalCount to keep track of the animals in that specific subsection.

When we run the code, it tells us the total number of animals in that subsection, which is 5. We can also access the areaAnimalCount variable defined in the outer code block, which is 10.

However, suppose we try to access the subsectionAnimalCount variable from outside the nested code block, such as after the closing curly brace `}`. We’ll get an error in that case because it only exists within that specific block. It’s like a secret toy that can only be played with inside a particular nesting doll.

The concept of lexical scope is valuable because it allows variables and functions to be accessed within their own code blocks and any nested code blocks inside.

In conclusion, understanding scopes allows us to keep our code organised and prevent conflicts between different parts of our program. It’s like ensuring our toys are in the right places so that we can find and play with them easily. Remember, global scope is like having toys for the whole house, the local scope is like toys just for your room, and function/block scope is like toys specific to certain rooms or hidden treasure chests.

--

--

Megan Tipps
Megan Tipps

Written by Megan Tipps

Experienced Vue.js dev & team lead. Passionate about maintainable code, latest front-end tech, and enhancing user experience. Skilled in leadership.

No responses yet