HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Immutability in functional programming

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
programmingimmutabilityjavascriptfunctional

Problem

In traditional programming, data is often mutable, meaning that it can be manipulated and altered at will after it is created. Let's look at an example:
In functional programming, however, data is treated as immutable, meaning it cannot be changed once it is created. Instead of modifying data, new data is created based on the old data. This helps prevent unintended consequences and makes it easier to reason about the program.
As you can see in the example above, the original array is not modified. Instead, a new array is created based on the old array. The original array is still available and can be used elsewhere in the program, if needed.
@Further reading
> [!NOTE]

Solution

let arr = [1, 2, 3];
arr.push(4); // `arr` is now [1, 2, 3, 4]


As you can see in the example above, the original array is not modified. Instead, a new array is created based on the old array. The original array is still available and can be used elsewhere in the program, if needed.
@Further reading
> [!NOTE]
>
> In both examples, the array is technically mutable, regardless of the way it is created (using let or const). However, in the first example, the array is mutated via the use of Array.prototype.push(), while in the second example, the array is not mutated. This is because Array.prototype.push() mutates the array in-place, while the spread operator (...) creates a new array.

Code Snippets

let arr = [1, 2, 3];
arr.push(4); // `arr` is now [1, 2, 3, 4]
const arr = [1, 2, 3];
const newArr = [...arr, 4];
// `newArr` is [1, 2, 3, 4], `arr` is still [1, 2, 3]

Context

From 30-seconds-of-code: immutability

Revisions (0)

No revisions yet.