2024-09-03 08:40:40 +02:00

75 lines
2.0 KiB
Plaintext

== Why is this an issue?
Using `var` or `let` to export mutable variables in JavaScript can lead to unpredictable behavior and bugs, as any module that imports them can change their values.
This complicates debugging and reduces code readability, as it's difficult to understand the flow and state of the application.
Avoiding mutable exports helps maintain data integrity and makes your code more reliable.
== How to fix it
When you need to export a variable, use `const` to ensure it remains immutable. This prevents other modules from altering its value.
If you need to export data that might change, consider exporting functions that return the data instead of exporting the data directly. This way, you can control how and when the data is modified.
Consider using immutable data structures, such as those provided by libraries like https://www.npmjs.com/package/immutable[Immutable.js], to manage data that should not change. This can help you maintain data integrity and avoid unintended side effects.
=== Code examples
==== Noncompliant code example
[source,javascript,diff-id=1,diff-type=noncompliant]
----
let port = 8080
export { port }; // Noncompliant
----
==== Compliant solution
[source,javascript,diff-id=1,diff-type=compliant]
----
const port = 8080
export { port };
----
==== Noncompliant code example
[source,javascript,diff-id=2,diff-type=noncompliant]
----
let counter = 0;
export { counter }; // Noncompliant
----
==== Compliant solution
[source,javascript,diff-id=2,diff-type=compliant]
----
let counter = 0;
const getCounter = () => counter;
const incrementCounter = () => { counter += 1; };
export { getCounter, incrementCounter };
----
==== Noncompliant code example
[source,javascript,diff-id=3,diff-type=noncompliant]
----
let settings = {
theme: "dark",
language: "en"
};
export { settings }; // Noncompliant
----
==== Compliant solution
[source,javascript,diff-id=3,diff-type=compliant]
----
import { Map } from 'immutable';
const settings = Map({
theme: "dark",
language: "en"
});
export { settings };
----