const keyword vs let keyword in JavaScript
Hello guys, sorry to disturb you all; I've just started to learn JavaScript and the use of the const keyword and let keyword seems confusing, like I don't really know when to use which.... can't I always use the let keyword ? Is that a bad idea? If so, can someone just clarify when we should use the const keyword and when we should use the let keyword please
21 Replies
you can use let for everything
you should use
const
when you know that the value won't changethis is what happens
however, you can change an object if it is assigned to a constant
but you can't assign anything else
a few good uses for
const
s are dom elements and anonymous functionsI'd recommend inverting that. Use
const
, unless you know your value will change, or you can't set the value at declaration timei dont recommend that for new developers for one reason: people make mistakes, and may try to assign to a constant without noticing it, and then ask why it doesn't work
The error is pretty self explanatory
yeah, but do people even read those before asking questions?
yep got it, thanks guys !
you're welcome
what do you mean by "we can't set the value at declaration time"... can you give an example please
they should, and I honestly don't think that's a reason to advise a suboptimal practice. Cause you can always just teach them to read that error message next, and they have a good habit to build on
ah you mean like a counter?
sometimes, you need to declare a variable in a certain scope, but the value depends on a condition:
if you declare the test variable inside those blocks, you'll end up with the variable going out of scope at the closing bracket, so you have to have the declaration outside
my own way of working with let and const is to just always use const and then my IDE yells at me if I assign to it. At that point, you think "Hmm, should I be assigning to this variable?" and change it to let as needed
yeah I see, JS is block-level scope I think...that's why we should declare the variable test outside of the block ?
yeah
Yep I see, it's clearer now, ty !!
there's cases with for or while loops too, and a bunch of others with callbacks and closures, but it's usually a scope issue
true, but it's easier to use constants when you know you need them, instead of using them for everything
And safer to use them by default
i agree
but to achieve "true" type safety, its better to just use typescript