Const in javascript? When to use it and is it necessary

Const in javascript? When to use it and is it necessary


I’ve recently come across the const keyword in javascript. From what i can tell, it is used to create immutable variables, and I’ve tested to ensure that it cannot be redefined (in node.js):

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?

Problem courtesy of: axdg


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 technical difference is significant. In compiled languages, a constant will be replaced at compile-time and its use will allow for other optimizations like dead code removal to further increase the runtime efficiency of the code. Recent (loosely used term) JavaScript engines actually compile JS code to get better performance, so using the const keyword would inform them that the optimizations described above are possible and should be done. This results in better performance.

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.

Solution courtesy of: Tibos


Leave a Reply

Your email address will not be published. Required fields are marked *