Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJames Reynolds
3,182 PointsWhy use const?
So far I haven't seen any explanation as to why Porth, is setting variables using const. Why is this the case?
2 Answers
Matthew Long
28,407 PointsThe basic rule of thumb I use is:
- never use
var
- use
const
when you're not going to reassign the identifier (not to be confused with immutable values) - use
let
when you're going to reassign the identifier
James Reynolds
3,182 PointsJames Reynolds
3,182 PointsThanks for your reply Matt, I just want to make sure I have this right. As far I understand 'let' creates a local scope for the block it's in, and even though that's the case you never need var? So either you don't need to change the value and you use 'const' or you may need to change the value but if you do its scope won't be an issue in which case you should use 'let'. Am I missing anything with that summary? Also, I suppose it is possible that I am confusing the way 'const' works with immutable values. I know both can't be changed but what makes them distinct from one another? Thanks, again for taking the time to help me.
Matthew Long
28,407 PointsMatthew Long
28,407 PointsBasically. Yes.
var
is function scope whilelet
andconst
are block scope. Any time you've got a set of curly braces you have block scope. Usingvar
can cause a lot of bugs which is why a large number of developers don't use it anymore.Immutable means something can't be changed. With
const
things can be changed, but not reassigned. So array methods for example, work withconst
.let
can be reassigned,const
cannot be.James Reynolds
3,182 PointsJames Reynolds
3,182 PointsOkay, thank you very much for taking the time to clear that up for me.