DEV Community

loading...
Cover image for `let` vs `const` and The Mental Mass of Functions

`let` vs `const` and The Mental Mass of Functions

katzy687 profile image Natti Katz ・2 min read

let is the new var?

So this revelation of sorts was presented to me during a code review. "Why did you use let here? I don't see it changing anywhere in this function?"

Well you see, I began to explain, nearly every es6 tutorial I've seen declares let as the new de-facto var (with block scoping). Grab let as your go-to variable unless you know for a fact that you don't need to re-assign it - in that case you can use const. This seemed like a good approach to me, keeps my variables flexible until I choose to explicitly restrict them.

const first approach

"No, no, no" he began. "You should reach for const by default, and only if you intend for the variable to change should you use let. As soon as I see a let I start to look for where it will be reassigned. If you use const I can simply forget about it and have one less thing to think about."

mind blown

This made so much sense to me that I'm kinda surprised it's not the default recommendation. This approach also fits right in with the functional/declarative approach to programming that I'm trying to adopt as it clearly states intent and minimizes distractions. It may seem like a minor change, but in more complex functions with multiple arguments and reassignments, this small change can be very helpful in reducing the cognitive load of the function.

Now instead of mindlessly using let 'just in case' I may want to re-assign later, I just grab const by default and in the event I'd like to re-assign halfway through a function, I'll go back and change it to a let.

Thanks for reading my first post on dev.to!

Discussion (5)

pic
Editor guide
Collapse
ztickm profile image
Salim MAHBOUBI • Edited

I remember my teachers telling me that const aren't that useful cause you can't change them...
Yeah that happens...

Collapse
benholio profile image
Ben Collier

ESLint comes in handy here - it will auto-fix your let (or var) to const if you never mutate it.

Collapse
katzy687 profile image
Natti Katz Author

Amazing! I just started using TSLint and it also gives me let and const recommendations. I probably should have started using a linter earlier. It took the angular cli including it by default with typescript to start linting.

Collapse
tobias_salzmann profile image
Tobias Salzmann • Edited

Imho, re-assigning a let with an immutable value should be preferred over mutating a const value though.

Collapse
katzy687 profile image
Natti Katz Author

that's a great point.

The method above is probably more useful with primitives.

In the case where I wanted to slice to a new array, or convert to an immutable data structure I would stick with let.

But the point remains that I wouldn't necessarily want to use let unless that I knew I was going to be doing some reassignment to preserve immutability.