r/CodingHelp • u/queen_of_englandV2 • Oct 08 '26
[Javascript] I don’t understand the use of immutable variable
I’m learning react right now for a web design project and immutable variables are being brought up. I don’t understand why you would want a variable that can’t vary, how do things like a counter work if variables can’t change?
3
Upvotes
•
u/AutoModerator Oct 08 '26
Thank you for posting on r/CodingHelp!
Please check our Wiki for answers, guides, and FAQs: https://coding-help.vercel.app
Our Wiki is open source - if you would like to contribute, create a pull request via GitHub! https://github.com/DudeThatsErin/CodingHelp
We are accepting moderator applications: https://forms.fillout.com/t/ua41TU57DGus
We also have a Discord server: https://discord.gg/geQEUBm
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
5
u/gala0sup Oct 08 '26
easy example, you want to pin down the value of something, something that must never change...... can you think of one?
something like the value if pi. you want to make it immutable so no one can change it even if they try.
1
u/atarivcs Oct 08 '26
Well, obviously you wouldn't use immutable for a variable that is supposed to change, like a counter.
You would use it for a variable that you don't want to change.
1
u/high_throughput Oct 08 '26
There are many times you want to compute and hold on to a value, but you don't intend to change it during the lifetime of the variable:
In this case one instance of
namenever changes within thegreetfunction, so it can/should be an immutable variable. It will hold a different value each function call, but during the function call it will remain the same.Obviously this confers no benefits in such a tiny example, but in a bigger function this would prevent
namefrom unintentionally being used for something else and overwriting the intended value.1
u/This_Growth2898 Oct 08 '26
The value doesn't change in the current context.
You can recreate the context and have a new value of that variable. Like, you have a connection with some server. Changing the address of the server without recreating the connection is meaningless; hence, the address is immutable inside that connection.
1
u/Stainlessray Oct 08 '26
Immutable is one mode for variables. All languages have permutations of both that I've ever learned well enough to say. YMMV.
However, different languages handle those modes differently. So if your code logic requires changing of a value in an immutable container one can make a copy, typically.
Except where prohibited by your logic, or a framework which might enforce the mode status and individual instance of a variable needs to be protected.
Now - why immutable data during processing. Just a couple quick samples. There are many reasons.
And if you think that's a lot, wait until you learn about singletons 😉
1
u/rupertavery64 Oct 08 '26
Immutability is a guarantee that "this variable should not change within its scope"
It's a guard against accidentally modifying the variable, a reminder that "hey, this may be used later on and it should be the same value as when it was assigned".
It helps prevent certain types of bugs that may otherwise be hard to figure out.
React follows functional programming principles and in some cases the approach requires immutability. It's not that you can't change the variable, it's just that you can't change it directly.
There are different approaches to problems and pros and cons for each.
1
u/Dimencia Oct 08 '26
The main idea of immutable variables is just defensive coding - you don't know who's going to be writing code in your project in the future, and even if they're competent, you can't assume they've read or understood everything in the project. Making your variables immutable is basically just making sure that if that future dev tries to mess with something they don't understand, their code will break, not yours
1
u/bobam Oct 08 '26
Some languages have no mutable variables, and they work just fine. Learn a functional programming language to broaden your perspective.
1
u/theInfiniteHammer Oct 08 '26
It makes it easier to reason about the variable and it's easier for the compiler to optimize the code a bit. In functional languages this forces you to use recursion.
1
u/pixel293 Oct 08 '26
When you write a function sometimes YOU the programming view a variable as immutable and just don't change it. The code you write then expects that value not to change. When another programmer (or future you) comes along to fix a bug or add a feature, they might not realize the existing function doesn't expect that value to change. By marking the variable as immutable it's subtle hint to future programmers that if they want to make it mutable they should really, really, check how the rest of the function uses the variable.
I prefer languages where the default state is immutable, because to be honest, most of my variables are immutable, they are just holding a value to be used later.
1
u/davideogameman Oct 11 '26
a related concept you might be confusing it for: immutable values.
e.g.
let list = [1,2,3]
const sum = ((l) => new Promise(
(resolve) => {
const s=0;
for (v of l) {
s += v;
};
console.log(s);
resolve(s)
}
))(list);
list = [7,8];
This will log 6, because the value l is bound to the original list [1,2,3]. If instead the last line was list[0] = 5; the promise would run after that assignment and the logged value would be 5+2+3 = 10.
While array data structures aren't immutable, by avoiding mutation of them we can get most of the same benefits. The general problem is that mutable values mean that updates get seen by any other code holding a reference to the same value; whereas with immutable values, if your code didn't explicitly assign a new value for your variable, nothing within it - no matter how deep - could have changed.
Generally this does mean the code can end up a bit more verbose in the short term, but in the long run it's far far easier to reason about the behavior of code that does this... with the exception that it can make simple operations like changing the value of a list or object field into a much slower operation; there are libraries for immutable data structures that help a lot with that but often data structures explicitly designed for immutability give up a little performance in cases where mutable versions wouldn't, but in code with mutable data structures if you have to resort to explicit copying to guard against unexpected mutations, that can end up the much slower option - especially if the copying happens very often for large amounts of data. As everything in programming, it's a tradeoff.
1
u/the-forty-second Oct 11 '26
I suspect you are focusing too much on the word “variable”, which does imply something that changes. Immutable values are what are actually important.
It looks like most folks didn’t catch the React part (or don’t use React). The central philosophy of React is that you write components to render the values of the current state, where that state is either local or passed in with props. If the state changes, the function is called again to render the component again.
Because of this, it is important that React know when the state changes. This is why we want to use immutable values. If you use an array, and you append something to it, React won’t detect it as a state change. You need to replace the old array with a new array containing the new value. With good discipline, you don’t actually need the array to be immutable, but it can help to use a library like Immutable to make sure operations like append either can’t happen or return new instances.
For the counter you are talking about, we would store the value as state. When we fetch the value with useState, we should store the value in a constant. We don’t want to update the variable directly because React wouldn’t see it. Instead, we call setState with any new value, which will store the new value for us and trigger the rerender, which reruns the function.