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 standardized 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 favor 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?

18 Answers
18

Leave a Comment