skip to Main Content

I already know that JavaScript uses const for constants and let for variables in variable declarations.

const SOME_VARIABLE = "TEST"
let SOME_VARIABLE = "TEST"

But I’ve seen them use let for constants as well.
I think there are pros and cons to that part, so I’d like to hear your thoughts.

What are the pros and cons of using let in a constant?
Should constant always use ‘const’ only?
I would appreciate it if you could tell me in detail what are the disadvantages of using the constant ‘let’.

What I heard about people using "let" for constants was that it was easy to change the initialization part of the short code.

3

Answers


  1. It depends on the purpose of your variable. If the value is ment to change, then use let. On the other hand, once you declare a const variable you will not be able to change the value nor redecalre the variable. However, if your const contains an object, you can mutate it.

    One similarity is that both are block-scoped variables.

    Here are some references on both :

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

    Disadvantage of let over const :

    One reason it is usualy advised to favor const over let is mutation (of objects), or changing the value of a variable. In general, you dont want your variables changing all the time because this leads to unexpected behavior, and it becomes increasingly dificult to understand what your variables contain. For exemple, this is especialy true if you have several functions that use the same variable, imagine all those functions changing the value but one of them expecting a specific one. And the unexpected behavior will only get worse as your code base grows.

    As other users have recomended, I also advise to use always const and use let only when you have a very specific need.

    Login or Signup to reply.
  2. There is no advantage. If you declare a variable as a constant, your programm will fail with an error when something tries to overwrite its value. Having a program fail under unexpected conditions is mostly better than getting some unexpected output.

    Use "let" only in cases here you explicitly want to allow a variable to be reassigned.

    Login or Signup to reply.
  3. There is a significant difference regarding the TypeScript type inference:

    const SOME_VARIABLE = "TEST"; // inferred as literal type "TEST"
    let SOME_VARIABLE2 = "TEST"; // inferred as type string
    

    Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search