52 lines
1.6 KiB
Plaintext
52 lines
1.6 KiB
Plaintext
![]() |
== Why is this an issue?
|
||
|
|
||
|
Side effects in a module can lead to unpredictable behavior, making the module harder to understand and debug.
|
||
|
They complicate testing by requiring complex setup and teardown procedures, reducing the module's reusability since its
|
||
|
behavior depends on specific states or external systems. Side effects can also introduce concurrency issues, such as
|
||
|
race conditions, and make the codebase harder to maintain and more prone to breaking. Additionally, they increase the
|
||
|
complexity and reduce the readability of the code, while breaking encapsulation and leading to tighter coupling between
|
||
|
modules. Minimizing side effects helps create more predictable, testable, reusable, and maintainable code.
|
||
|
|
||
|
=== Code examples
|
||
|
|
||
|
==== Noncompliant code example
|
||
|
|
||
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
||
|
----
|
||
|
console.log('hello world');
|
||
|
if (typeof Array.prototype.map !== 'function') {
|
||
|
Array.prototype.map = () => {
|
||
|
// Implement polyfill
|
||
|
};
|
||
|
}
|
||
|
let s = 0;
|
||
|
for (let i = 0; i < 10; i++) {
|
||
|
s += i;
|
||
|
}
|
||
|
fetch('/api').then((res) => res.text());
|
||
|
----
|
||
|
|
||
|
|
||
|
==== Compliant solution
|
||
|
|
||
|
[source,javascript,diff-id=1,diff-type=compliant]
|
||
|
----
|
||
|
export default function () {
|
||
|
console.log('hello world');
|
||
|
|
||
|
let s = 0;
|
||
|
for (let i = 0; i < 10; i++) {
|
||
|
s += i;
|
||
|
}
|
||
|
|
||
|
fetch('/api').then((res) => res.text());
|
||
|
}
|
||
|
----
|
||
|
|
||
|
== Resources
|
||
|
=== Documentation
|
||
|
|
||
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules[Modules]
|
||
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import[import]
|
||
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export[export]
|