[javascript] 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.

So my questions are:

  • 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?

This question is related to javascript node.js constants immutability

The answer is


When it comes to the decision between let and const (both block scoped), always prefer const so that the usage is clear in the code. That way, if you try to redeclare the variable, you'll get an error. If there's no other choice but redeclare it, just switch for let. Note that, as Anthony says, the const values aren't immutable (for instances, a const object can have properties mutated).

When it comes to var, since ES6 is out, I never used it in production code and can't think of a use case for it. One point that might consider one to use it is JavaScript hosting - while let and const are not hoisted, var declaration is. Yet, beware that variables declared with var have a function scope, not a block scope («if declared outside any function, they will be globally available throughout the program; if declared within a function, they are only available within the function itself», in HackerRank - Variable Declaration Keywords). You can think of let as the block scoped version of var.


Main point is that how to decide which one identifier should be used during development.
In java-script here are three identifiers.

1. var (Can re-declared & re-initialize)
2. const (Can't re-declared & re-initialize, can update array values by using push)
3. let (Can re-initialize but can't re-declare)

'var' : At the time of codding when we talk about code-standard then we usually use name of identifier which one easy to understandable by other user/developer. For example if we are working thought many functions where we use some input and process this and return some result, like:

**Example of variable use**

function firstFunction(input1,input2)
{
 var process = input1 + 2; 
 var result = process - input2;
 return result;
}


function otherFunction(input1,input2)
{
 var process = input1 + 8; 
 var result = process * input2;
 return result;
}

In above examples both functions producing different-2 results but using same name of variables. Here we can see 'process' & 'result' both are used as variables and they should be.

 **Example of constant with variable**

 const tax = 10; 
 const pi = 3.1415926535; 

function firstFunction(input1,input2)
{
 var process = input1 + 2; 
 var result = process - input2;
 result = (result * tax)/100; 
 return result;
}


function otherFunction(input1,input2)
{
 var process = input1 + 8; 
 var result = process * input2 * pi;
 return result;
}

Before using 'let' in java-script we have to add ‘use strict’ on the top of js file

 **Example of let with constant & variable**

 const tax = 10; 
 const pi = 3.1415926535; 
 let trackExecution = '';

function firstFunction(input1,input2)
{
 trackExecution += 'On firstFunction'; 
 var process = input1 + 2; 
 var result = process - input2;
 result = (result * tax)/100; 
 return result;
}


function otherFunction(input1,input2)
{
 trackExecution += 'On otherFunction'; # can add current time 
 var process = input1 + 8; 
 var result = process * input2 * pi;
 return result;
}

 firstFunction();
 otherFunction();
 console.log(trackExecution);

In above example you can track which one function executed when & which one function not used during specific action.


var: Declare a variable, value initialization optional.

let: Declare a local variable with block scope.

const: Declare a read-only named constant.

Ex:

var a;
a = 1;
a = 2;//re-initialize possible
var a = 3;//re-declare
console.log(a);//3

let b;
b = 5;
b = 6;//re-initiliaze possible
// let b = 7; //re-declare not possible
console.log(b);

// const c;
// c = 9;   //initialization and declaration at same place
const c = 9;
// const c = 9;// re-declare and initialization is not possible
console.log(c);//9
// NOTE: Constants can be declared with uppercase or lowercase, but a common
// convention is to use all-uppercase letters.

In my experience I use const when I want to set something I may want to change later without having to hunt through the code looking for bits that have been hard coded e.g. A file path or server name.

The error in your testing is another thing though, you are tring to make another variable called x, this would be a more accurate test.

const x = 'const';
x = 'not-const';

It provides:

  1. a constant reference, eg const x = [] - the array can be modified, but x can't point to another array; and

  2. block scoping.

const and let will together replace var in ecma6/2015. See discussion at https://strongloop.com/strongblog/es6-variable-declarations/


Personal preference really. You could use const when, as you say, it will not be re-assigned and is constant. For example if you wanted to assign your birthday. Your birthday never changes so you could use it as a constant. But your age does change so that could be a variable.


The semantics of var and let

var and let are a statement to the machine and to other programmers:

I intend that the value of this assignment change over the course of execution. Do not rely on the eventual value of this assignment.

Implications of using var and let

var and let force other programmers to read all the intervening code from the declaration to the eventual use, and reason about the value of the assignment at that point in the program's execution.

They weaken machine reasoning for ESLint and other language services to correctly detect mistyped variable names in later assignments and scope reuse of outer scope variable names where the inner scope forgets to declare.

They also cause runtimes to run many iterations over all codepaths to detect that they are actually, in fact, constants, before they can optimise them. Although this is less of a problem than bug detection and developer comprehensibility.

When to use const

If the value of the reference does not change over the course of execution, the correct syntax to express the programmer's intent is const. For objects, changing the value of the reference means pointing to another object, as the reference is immutable, but the object is not.

"const" objects

For object references, the pointer cannot be changed to another object, but the object that is created and assigned to a const declaration is mutable. You can add or remove items from a const referenced array, and mutate property keys on a const referenced object.

To achieve immutable objects (which again, make your code easier to reason about for humans and machines), you can Object.freeze the object at declaration/assignment/creation, like this:

const Options = Object.freeze(['YES', 'NO'])

Object.freeze does have an impact on performance, but your code is probably slow for other reasons. You want to profile it.

You can also encapsulate the mutable object in a state machine and return deep copies as values (this is how Redux and React state work). See Avoiding mutable global state in Browser JS for an example of how to build this from first principles.

When var and let are a good match

let and var represent mutable state. They should, in my opinion, only be used to model actual mutable state. Things like "is the connection alive?".

These are best encapsulated in testable state machines that expose constant values that represent "the current state of the connection", which is a constant at any point in time, and what the rest of your code is actually interested in.

Programming is already hard enough with composing side-effects and transforming data. Turning every function into an untestable state machine by creating mutable state with variables just piles on the complexity.

For a more nuanced explanation, see Shun the Mutant - The case for const.


My opinions:

Q. When is it appropriate to use const in place of var?
A. Never!

Q: Should it be used every time a variable which is not going to be re-assigned is declared?
A: Never! Like this is going to make a dent in resource consumption...

Q. Does it actually make any difference if var is used in place of const or vice-versa?
A: Yes! Using var is the way to go! Much easier in dev tools and save from creating a new file(s) for testing. (var in not in place of const - const is trying to take var's place...)

Extra A: Same goes for let. JavaScript is a loose language - why constrict it?!?


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.


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)
}

with:

// Will output 'ANOTHER_SECRET'

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

or

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

const x = "SECRET"

/*  complex code */

var x = 0

with

// Will reassign y and cause trouble

var y = "SECRET"

/*  complex code */

var y = 0

'const' is an indication to your code that the identifier will not be reassigned. This is a good article about when to use 'const', 'let' or 'var' https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75#.ukgxpfhao


I am not an expert in the JS compiling business, but it makes sense to say, that v8 makes use from the const flag

Normally a after declaring and changing a bunch of variables, the memory gets fragmented, and v8 is stopping to execute, makes a pause some time of a few seconds, to make gc, or garbage collection.

if a variable is declared with const v8 can be confident to put it in a tight fixed size container between other const variables, since it will never change. It can also save the proper operations for that datatypes since the type will not change.


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.


First, three useful things about const (other than the scope improvements it shares with let):

  • It documents for people reading the code later that the value must not change.
  • It prevents you (or anyone coming after you) from changing the value unless they go back and change the declaration intentionally.
  • It might save the JavaScript engine some analysis in terms of optimization. E.g., you've declared that the value cannot change, so the engine doesn't have to do work to figure out whether the value changes so it can decide whether to optimize based on the value not changing.

Your questions:

When is it appropriate to use const in place of var?

You can do it any time you're declaring a variable whose value never changes. Whether you consider that appropriate is entirely down to your preference / your team's preference.

Should it be used every time a variable which is not going to be re-assigned is declared?

That's up to you / your team.

Does it actually make any difference if var is used in place ofconst` or vice-versa?

Yes:

  • var and const have different scope rules. (You might have wanted to compare with let rather than var.) Specifically: const and let are block-scoped and, when used at global scope, don't create properties on the global object (even though they do create globals). var has either global scope (when used at global scope) or function scope (even if used in a block), and when used at global scope, creates a property on the global object.
  • See my "three useful things" above, they all apply to this question.

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]
marks.push(95)
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 mutating the variable.

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.


Summary:

const creates an immutable binding meaning const variable identifier is not re-assignable.

const a = "value1";

you cannot re-assign it with

a = "value2";

However, if const identifier holds an object or an array, value of it can be changed as far as we are not re-assigning it.

const x = { a: 1 }

x.a = 2; //is possible and allowed

const numbers = [1, 2];
numbers.push(3); //is possible and allowed

Please note that const is a block-scoped just like let which is not same as var (which is function-scoped)

In short, When something is not likely to change through re-assignment use const else use let or var depending on the scope you would like to have.

It's much easier to reason about the code when it is dead obvious what can be changed through re-assignment and what can't be. Changing a const to a let is dead simple. And going const by default makes you think twice before doing so. And this is in many cases a good thing.


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to constants

Constants in Kotlin -- what's a recommended way to create them? Why Is `Export Default Const` invalid? Proper use of const for defining functions in JavaScript Declaring static constants in ES6 classes? How can I get the size of an std::vector as an int? invalid use of non-static member function Why does JSHint throw a warning if I am using const? Differences Between vbLf, vbCrLf & vbCr Constants Constant pointer vs Pointer to constant Const in JavaScript: when to use it and is it necessary?

Examples related to immutability

Enums in Javascript with ES6 Correct way to push into state array What is difference between mutable and immutable String in java Const in JavaScript: when to use it and is it necessary? Aren't Python strings immutable? Then why does a + " " + b work? String is immutable. What exactly is the meaning? Immutable vs Mutable types Java Immutable Collections Set System.Drawing.Color values Remove specific characters from a string in Python