I have been trying to find a good article on the advantages of
let. Unfortunately, all I get is a bunch of articles about how
var is dead (it’s not, and is different from both
const), and that you should abandon it for the new hotness. I agree, but on top of that, you should abandon mutability (almost) altogether in favor of a more declarative paradigm.
For those who don’t know what
const does, it is similar to
boolean are all passed by value. Which means that you get the following behavior:
Which makes a ton of sense, nothing new here or surprising. Where it gets interesting is when you try this same thing with an
object. They are _also_ immutable, but what is stored is not the object itself, but a reference. Think pointers. So when you try something similar to the above but with objects, you get a different result:
Now changing a property of
thing2 copied from
thing1 changes the property in
This also means that you are allowed to change the properties of an object assigned with
const, but you can’t re-assign the object itself:
You probably already knew this, but in case you didn’t already, you learned a little somethin’ somethin’ here.
Why is const/immutability important?
This is where we get into the best practice / not best practice, opinionated, subjective domain. Immutability more than anything gives you a single source of truth(mostly). A single source of truth is useful when tracking down bugs and errors in your code. When you run into an unexpected value in a variable while debugging, it’s good to know that you can jump to the variable definition and know that that was the only place where your variable could have been set (or mutated).
In other words, you get rid of side effects.
There is an exception to this, which is actually demonstrated by the code examples above. You can still mutate properties of an object set with
When talking about working in the context of React, this is good to know because of how react chooses whether or not to re-render a component. An object passed as a prop is compared with its ref, and if that ref changes, (even if the object is a copy of the one passed in) react will re-render.
The important part to look at is in the render function and the prop being passed. NEVER (or almost never, idk, you do you) create new objects as passed props. This is because you are creating a new object every time you render, which causes the objectRef to change, which React interprets as a new object that needs re-rendering.
Some struggles on how to use const
I have not run into a time where I couldn’t accomplish my task without solely using
const. Maybe it is the lack of knowledge around some handy utilities like
reduce() that people choose to create new objects, but there are not a lot of cases or reasons to use