Learn
Scope
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:
- 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.
- 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.
- 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:
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:
Instructions
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