front-end-interview-handbook/packages/quiz/questions/why-is-it-in-general-a-good.../en-US.mdx

86 lines
4.2 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?
---
## TL;DR
JavaScript that is executed in the browser has access to the global scope, and if everyone uses the global namespace to define their variables, collisions will likely occur. Use the module pattern (IIFEs) to encapsulate your variables within a local namespace.
### Example
#### Using global scope
```js
let count = 0;
function incrementCount() {
count++;
console.log(count);
}
function decrementCount() {
count--;
console.log(count);
}
incrementCount(); // Output: 1
decrementCount(); // Output: 0
```
In this example, `count`, `incrementCount`, and `decrementCount` are all defined in the global scope. Any script on the page can access and modify these variables and functions.
#### Using IIFE (Immediately invoked function expression)
```js
(function () {
let count = 0;
window.incrementCount = function () {
count++;
console.log(count);
};
window.decrementCount = function () {
count--;
console.log(count);
};
})();
incrementCount(); // Output: 1
decrementCount(); // Output: 0
```
In this example, `count` is not accessible in the global scope. It can only be accessed and modified by the `incrementCount` and `decrementCount` functions. These functions are exposed to the global scope by attaching them to the `window` object, but they still have access to the `count` variable in their parent scope. This provides a way to encapsulate data and avoid polluting the global scope.
---
In JavaScript, it is very easy to define variables and functions in global scope. You can declare a variable globally by simply assigning a value to it outside of any function:
```js
var myGlobalVar = 'Hello World';
```
Global variables are accessible from anywhere in your JavaScript code. It's generally recommended to avoid using global variables whenever possible due to following reasons:
1. **Global Variables are Considered a "Bad Thing"**: Global variables are generally considered a bad practice in most programming languages, including JavaScript. They can lead to code that is harder to read, maintain, and debug.
2. **Unpredictable Behavior**: Global variables can be updated from any point in the program, making it difficult to predict their values. This can lead to unexpected behavior and side effects.
3. **Name Clashes**: Since there is only one global namespace, it is more likely to encounter name clashes with other variables or libraries. This can cause conflicts and errors.
4. **Performance and Implementation Complexity**: The global object in JavaScript can negatively impact performance and make the implementation of variable scoping more complicated.
5. **Less Modular Code**: Global variables can lead to less modular code, making it harder to reuse and maintain different parts of the program independently
### How to avoid global scope pollution
To avoid polluting the global scope in JavaScript, consider the following strategies:
1. **Use local variables**: Declare variables within functions or blocks to limit their scope and prevent them from being accessed globally. Use var, let, or const to declare variables within a specific scope, ensuring they are not accidentally made global
2. **Pass variables as function parameters:**: Instead of accessing variables directly from the outer scope, pass them as parameters to functions to maintain encapsulation and avoid global scope pollution.
3. **Use immediately invoked function expressions (IIFE)**: Wrap your code in an IIFE to create a new scope, preventing variables from being added to the global scope unless you explicitly expose them.
4. **Use modules**: Utilize module systems to encapsulate your code and prevent global scope pollution. Each module has its own scope, making it easier to manage and maintain your code.
## Further reading
- [JS: dont touch the global scope](https://lucybain.com/blog/2014/js-dont-touch-global-scope/)
- [Variables: Scopes, Environments, and Closures](https://exploringjs.com/es5/ch16.html)
- [JavaScript modules - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)
- [Modules, introduction](https://javascript.info/modules-intro)