⌚ Applying `Const` in Code... Real Time

So I’m gonna be honest… I’m still not quite sure as to why we need to use the variable const since the value is not allowed to change. What are the benefits of using this variable versus just writing out the value (assuming it’s not too big or complicated of one) every time? I feel like an example can really help me see this. Thanks in advance!

Just because the value won’t change, doesn’t mean that you know what it will be while you’re writing the code. It’s also useful when defining functions, so you don’t accidentally overwrite them later on in your code:

function someName(someParam) {
  //  do important stuff
  //  return important value
}
// a few hundred lines later...
// accidentally use the wrong variable
someName = 'pizza';
// many lines later...
// try to call the function:
let result = someName(someImportantArgument);
// TypeError: someName is not a function
// Now you're left trying to figure out how a function you know you defined isn't a function
// Versus
const someName = someParam => {
  // do important stuff
  // return important value
}
// Now when you accidentally do:
someName = 'pizza';
// You'll get this error which will be much easier to track down since it will include the line where you
// make the errant assignment
// TypeError: Assignment to constant variable.

I always use const unless I need to use let. Many variables in code get assigned to values that don’t need to change. You can always change const to let when you need to. A quick search will turn up many articles on using const versus let.

2 Likes

@midlindner Your explanation helped me understand a lot better. I feel like I definitely need to get more used to functions, but I got the gist of your example. Thank you so much! Very much appreciated.

1 Like