It may seem like a great idea to always make your variables accessible but global variables can cause problems in a program.
When you declare global variables, they go to the global namespace. The global namespace allows the variables to be accessible from anywhere in the program. These variables remain there until the program finishes, which means that our global namespace can fill up really quickly.
Scope pollution is when we have too many global variables that exist in the global namespace or when we reuse variables across different scopes. Scope pollution makes it difficult to keep track of our different variables and sets us up for potential accidents. For example, globally scoped variables can collide with other variables that are more locally scoped, causing unexpected behaviour in our code.
Let’s look at an example of scope pollution in practice so we know how to avoid it:
let num = 50;
const logNum = () => {
num = 100;
console.log(num);
};
logNum(); // Prints 100
console.log(num); // Prints 100
You’ll notice:
- We have a variable
num
. - Inside the function body of
logNum()
, we want to declare a new variable but forgot to use thelet
keyword. - When we call
logNum()
,num
gets reassigned to100
. - The reassignment inside
logNum()
affects the global variablenum
. - Even though the reassignment is allowed and we won’t get an error, if we decided to use
num
later, we’ll unknowingly use the new value ofnum
.
While it’s important to know what global scope is, it’s best practice to not define variables in the global scope.