Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    6Topics
    |
    6 Quizzes
Lesson 5, Topic 5
In Progress

JavaScript: Scope Pollution

Yasin Cakal 10 Nov 2021
Lesson Progress
0% Complete

While it may appear that making your variables accessible all of the time is a good idea, having too many global variables can cause problems in a program.

Global variables are declared in the global namespace. The variables in the global namespace can be accessed from anywhere in the program. These variables are kept in the global namespace until the program is finished, which means our global namespace can quickly fill up.

Scope pollution occurs when there are too many global variables in the global namespace, or when variables are reused across scopes. Scope pollution makes it difficult to keep track of all of our variables, putting us at risk of  mismanagement of variables. For example, globally scoped variables may collide with other locally scoped variables, resulting in unexpected behavior in our code.

Let’s look at a real-world example of scope pollution to see how we can avoid it:

let alpha = "a";
const logAlphabet = () => {
  alpha = "b";       // NOTICE THIS STATEMENT
  console.log(alpha);
};
 
logAlphabet(); // Prints b
console.log(alpha); // Prints b

You’ll notice that our alpha is variable.

  • We want to declare a new variable within the function body of logAlphabet(), but we forgot to use the let keyword.
  • When we call logAlphabet(), we reassign alpha to b.
  • The reassignment within logAlphabet() has an impact on the global variable alpha. Even though the reassignment is permitted and will not result in an error, if we use alpha later, we will unknowingly use the new value of alpha.

While it is important to understand what global scope is, it is not a good practice to define variables in the global scope.

Responses

Leave a Reply

%d bloggers like this: