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?


Solution 1:

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 2:

2017 Update

This answer still receives a lot of attention. It’s worth noting that this answer was posted back at the beginning of 2014 and a lot has changed since then. support is now the norm. All modern browsers now support const so it should be pretty safe to use without any problems.

Original Answer from 2014

Despite having fairly decent browser support, I’d avoid using it for now. From MDN’s article on const:

The current implementation of const is a Mozilla-specific extension and is not part of ECMAScript 5. It is supported in Firefox & Chrome (V8). As of Safari 5.1.7 and Opera 12.00, if you define a variable with const in these browsers, you can still change its value later. It is not supported in Internet Explorer 6-10, but is included in Internet Explorer 11. The const keyword currently declares the constant in the function scope (like variables declared with var).

It then goes on to say:

const is going to be defined by ECMAScript 6, but with different semantics. Similar to variables declared with the let statement, constants declared with const will be block-scoped.

If you do use const you’re going to have to add in a workaround to support slightly older browsers.

Solution 3:

To integrate the previous answers, there’s an obvious advantage in declaring constant variables, apart from the performance reason: if you accidentally try to change or re-declare them in the code, the program will respectively not change the value or throw an error.

For example, compare:

// Will output 'SECRET'

const x = 'SECRET'
if (x = 'ANOTHER_SECRET') {  // Warning! assigning a value variable in an if condition
    console.log (x)


// Will output 'ANOTHER_SECRET'

var y = 'SECRET'
if (y = 'ANOTHER_SECRET') { 
    console.log (y)


// Will throw TypeError: const 'x' has already been declared

const x = "SECRET"

/*  complex code */

var x = 0


// Will reassign y and cause trouble

var y = "SECRET"

/*  complex code */

var y = 0

Solution 4:

const is not immutable.

From the MDN:

The const declaration creates a read-only reference to a value. It
does not mean the value it holds is immutable, just that the variable
identifier cannot be reassigned.

Solution 5:

For why to use const, @Tibos’s answer’s great.

But you said:

From what i can tell, it is used to create immutable variables

That is wrong. Mutating a variable is different from reassigning:

var hello = 'world' // assigning
hello = 'bonjour!' // reassigning

With const, you can not do that:

const hello = 'world'
hello = 'bonjour!' // error

But you can mutate your variable:

const marks = [92, 83]
console.log(marks) // [92, 83, 95] -> the variable has been mutated.

So, any process that changes the variable’s value without using the = sign is muting.

Note: += for example is … re-assigning!

var a = 5
a += 2 // is the same as a = a + 2

So, the bottom line is: const doesn’t prevent you from mutating variables, it prevents you from re-assigning them.

Solution 6:

You have great answers, but let’s keep it simple.

const should be used when you have a defined constant (read as: it won’t change during your program execution).

For example:

const pi = 3.1415926535

If you think that it is something that may be changed on later execution then use a var.

The practical difference, based on the example, is that with const you will always asume that pi will be 3.14[…], it’s a fact.

If you define it as a var, it might be 3.14[…] or not.

For a more technical answer @Tibos is academically right.