Const vs let

I’m seeing a trouble occurring in regard to var/const/let, where people are saying use let instead of var. For example, in Coding Challenge #73: Acrostic at 5:23

For some, always using let is a simpler way because you then don’t have to think about when to use const versus let, but that’s just wrong. We need to be thinking about our code.

It’s more appropriate to use const instead of let, because it’s preferable to use constants instead of reassigning back to the same variable. Using constants simplifies the code and makes it more predictable, because you know that the value cannot change.

For example:

const button = document.querySelector("#submitbutton");
const input = document.querySelector("#wordinput");

The general rule is always use const, and only switch to let when you need it to change, such a with a counter.
There’s a good piece about const/let at Let’s use const! Here’s why. that dives deeper in to the topic.

2 Likes

I think about this as being similar to the principle of least privilege. You go with the most restrictive option first, and change as needed.

4 Likes

Agreed and that can be applied beyond JavaScript to any language and will help you leaps and bounds in preventing mistakes or exposing more than necessary to calling applications/classes. As if you get in the habit of returning an interface of a collection or an IEnumerable, you limit what the end user can do to the collection you pass them (to pretty much read-only).

Definitely a good principle to get in the habit of.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.