Code highlights logo



Scope Pollution

Scope pollution occurs when we have too many variables in the same scope or when we reuse variable names across different scopes. It can lead to unintended consequences and hard-to-find bugs in our programs.

Scope pollution can occur in different ways, such as:

  1. Reusing Variables: When we reuse variable names in different parts of our code, it becomes difficult to track and understand the value of each variable. This can lead to unexpected behavior and errors.
  2. Global Variables: Declaring variables in the global scope can cause scope pollution. Global variables are accessible from any part of the code, which can make it challenging to determine where and when a variable is modified.
  3. Unnecessary Variables: Declaring variables that are not needed or never used can clutter our code and make it harder to read and understand. It is important to avoid unnecessary variables to keep our code clean and maintainable.

Here's an example that demonstrates scope pollution:

1var globalVariable;
3function firstFunction() {
4 // This variable is declared without any keyword, making it global
5 globalVariable = 'I am global!';
8function secondFunction() {
9 // This function can access the global variable, even though it's not needed here
10 console.log(globalVariable); // Outputs: 'I am global!'
14secondFunction(); // This will log the globalVariable, even though it's not defined within this function

In this example, globalVariable is declared without any keyword inside firstFunction, making it a global variable. This pollutes the global scope, as globalVariable is now accessible from anywhere in the code, including inside secondFunction, where it's not needed.

A better approach would be to limit the scope of the variable by using the let or const keyword:

1function firstFunction() {
2 // This variable is now limited to the scope of firstFunction
3 let localVariable = 'I am local!';
6function secondFunction() {
7 // localVariable is not accessible here
8 console.log(localVariable); // ReferenceError: localVariable is not defined
12secondFunction(); // This will throw an error, as localVariable is not defined in this scope



Inside the exampleFunction(), declare another variable num with a value of 200.


Console.log this new num variable inside the exampleFunction().


Outside exampleFunction(), console.log the num variable again.

Sign up to start coding

Already have an account?

Sign In

Course content