const x = 'const'; const x = 'not-const'; // Will give an error: 'constant 'x' has already been defined'
I realise that it is not yet standardised across all browsers – but I’m only interested in the context of node.js/v8, and I’ve noticed that certain developers / projects seem to favour it heavily when the var keyword could be used to the same effect.
When is it appropriate to use const in place of var?
Should it be used every time a variable which is not going to be re-assigned is declared?
Does it actually make any difference if var is used in place of const or vice-versa?
There are two aspects to your questions: what are the technical aspects of using
const instead of
var and what are the human-related aspects of doing so.
The human-related aspect is about the semantics of the keyword. A variable is a data structure that contains information that is expected to change. A constant is a data structure that contains information that will never change. If there is room for error,
var should always be used. However, not all information that never changes in the lifetime of a program needs to be declared with
const. If under different circumstances the information should change, use
var to indicate that, even if the actual change doesn’t appear in your code.