r/functionalprogramming • • Apr 21 '25

Question mutable concept confusion

hello,FP newcomer here, is this considered to be functional? if not how can we implement global state in any application.a good resources that explain this part is appreciated

// Pure function to "increment" the counter
const increment = (count) => count + 1;

// Pure function to "decrement" the counter
const decrement = (count) => count - 1;

// Pure function to "reset" the counter
const reset = () => 0;

// Example usage:
let count = 0;
count = increment(count); // count is now 1
count = increment(count); // count is now 2
count = decrement(count); // count is now 1
count = reset();          // count is now 0
10 Upvotes

22 comments sorted by

View all comments

Show parent comment

1

u/KhepriAdministration Apr 27 '25

This creates a new variable, also called x, of the corresponding value. The new x "shadows" the old x, meaning any reference to x will get the new value (until this x goes out of scope, at which point the most recent in-scope x will be the the value referred to when writing "x".)

The shadowing-vs-mutating distinction is subtle but important. For example, if you have the following code:

let x = 1
let f = () => x + 1
let x = 3
print(f())

Then, when f is created, x refers to 1, so f equals () => 1 + 1. Reassigning x afterwards has no effect on f, so this code returns 2.

1

u/Level_Fennel8071 Apr 28 '25

where is the shadowing in your example??? is shadowing can be in same scope, pls explain further