75 lines
2.0 KiB
Plaintext
Raw Normal View History

2024-09-02 17:20:10 +02:00
== Why is this an issue?
2024-09-02 14:51:34 +00:00
2024-09-02 17:20:10 +02:00
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.
2024-09-02 14:51:34 +00:00
2024-09-02 17:20:10 +02:00
== How to fix it
2024-09-02 14:51:34 +00:00
When you need to export a variable, use `const` to ensure it remains immutable. This prevents other modules from altering its value.
2024-09-02 14:51:34 +00:00
2024-09-02 17:20:10 +02:00
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.
2024-09-02 14:51:34 +00:00
2024-09-02 17:20:10 +02:00
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.
2024-09-02 14:51:34 +00:00
=== Code examples
==== Noncompliant code example
[source,javascript,diff-id=1,diff-type=noncompliant]
----
2024-09-02 17:20:10 +02:00
let port = 8080
export { port }; // Noncompliant
2024-09-02 14:51:34 +00:00
----
==== Compliant solution
[source,javascript,diff-id=1,diff-type=compliant]
----
2024-09-02 17:20:10 +02:00
const port = 8080
export { port };
2024-09-02 14:51:34 +00:00
----
2024-09-02 17:20:10 +02:00
==== Noncompliant code example
2024-09-02 14:51:34 +00:00
2024-09-02 17:20:10 +02:00
[source,javascript,diff-id=2,diff-type=noncompliant]
----
let counter = 0;
export { counter }; // Noncompliant
2024-09-02 17:20:10 +02:00
----
2024-09-02 14:51:34 +00:00
2024-09-02 17:20:10 +02:00
==== Compliant solution
2024-09-02 14:51:34 +00:00
2024-09-02 17:20:10 +02:00
[source,javascript,diff-id=2,diff-type=compliant]
----
let counter = 0;
const getCounter = () => counter;
const incrementCounter = () => { counter += 1; };
export { getCounter, incrementCounter };
----
2024-09-02 14:51:34 +00:00
2024-09-02 17:20:10 +02:00
==== Noncompliant code example
[source,javascript,diff-id=3,diff-type=noncompliant]
----
let settings = {
theme: "dark",
language: "en"
};
export { settings }; // Noncompliant
2024-09-02 17:20:10 +02:00
----
==== Compliant solution
[source,javascript,diff-id=3,diff-type=compliant]
----
import { Map } from 'immutable';
const settings = Map({
theme: "dark",
language: "en"
});
export { settings };
----