Home:ALL Converter>Const in JavaScript: when to use it and is it necessary?

Const in JavaScript: when to use it and is it necessary?

Ask Time:2014-01-20T22:56:15         Author:axdg

Json Formatter

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?

Author:axdg,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/21237105/const-in-javascript-when-to-use-it-and-is-it-necessary
Edgar Griñant :

You have great answers, but let's keep it simple.\nconst should be used when you have a defined constant (read as: it won't change during your program execution).\nFor example:\nconst pi = 3.1415926535\n\nIf you think that it is something that may be changed on later execution then use a var.\nThe practical difference, based on the example, is that with const you will always assume that pi will be 3.14[...], it's a fact.\nIf you define it as a var, it might be 3.14[...] or not.\nFor a more technical answer, Tibos' is academically right.",
Sam Washington :

I am not an expert in the JavaScript compiling business, but it makes sense to say, that V8 makes use of the const flag.\nNormally 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 garbage collection, or garbage collection.\nIf a variable is declared with const, V8 can be confident to put it in a tightly fixed-size container between other const variables, since it will never change.\nIt can also save the proper operations for that datatypes since the type will not change.",
Funkotron_King :

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.\nThe error in your testing is another thing though. You are trying to make another variable called x, and this would be a more accurate test:\nconst x = 'const';\nx = 'not-const';\n",
Cjmarkham :

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.",
Tejas Patel :

Summary:\nconst creates an immutable binding, meaning a const variable identifier is not reassignable.\nconst a = "value1";\n\nYou cannot reassign it with\na = "value2";\n\nHowever, if the const identifier holds an object or an array, the value of it can be changed as far as we are not reassigning it.\nconst x = { a: 1 }\n\nx.a = 2; // Is possible and allowed\n\nconst numbers = [1, 2];\nnumbers.push(3); // Is possible and allowed\n\nPlease note that const is a block-scoped just like let which is not same as var (which is function-scoped).\nIn short, when something is not likely to change through reassignment use const, else use let or var, depending on the scope you would like to have.\nIt's much easier to reason about the code when it is dead obvious what can be changed through reassignment 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.",
Tibos :

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.\n\nThe 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.\n\nThe 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.",
Josh Wulf :

The semantics of var and let\n\nvar and let are a statement to the machine and to other programmers: \n\n\n I intend that the value of this assignment change over the course of execution. Do not rely on the eventual value of this assignment.\n\n\nImplications of using var and let\n\nvar 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.\n\nThey 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.\n\nThey 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.\n\nWhen to use const\n\nIf 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.\n\n\"const\" objects\n\nFor 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. \n\nTo 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:\n\nconst Options = Object.freeze(['YES', 'NO'])\n\n\nObject.freeze does have an impact on performance, but your code is probably slow for other reasons. You want to profile it.\n\nYou 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.\n\nWhen var and let are a good match\n\nlet and var represent mutable state. They should, in my opinion, only be used to model actual mutable state. Things like \"is the connection alive?\".\n\nThese 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.\n\nProgramming 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.\n\nFor a more nuanced explanation, see Shun the Mutant - The case for const.",
James Donnelly :

2017 Update\n\nThis 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. ecmascript-6 support is now the norm. All modern browsers now support const so it should be pretty safe to use without any problems.\n\n\n\nOriginal Answer from 2014\n\nDespite having fairly decent browser support, I'd avoid using it for now. From MDN's article on const:\n\n\n 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).\n\n\nIt then goes on to say:\n\n\n 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.\n\n\nIf you do use const you're going to have to add in a workaround to support slightly older browsers.",
vinod :

The main point is that how to decide which one identifier should be used during development.\nIn JavaScript here are three identifiers.\n\nvar (Can redeclared and reinitialize)\nconst (Can't redeclared and reinitialize, and can update array values by using push)\nlet (can reinitialize, but can't redeclare)\n\n\n'var': At the time of coding when we talk about code standards, then we usually use the name of an identifier which is one that is easy to understand by other users and developers.\n\nFor example, if we are working thought many functions where we use some input and process this and return some result, like:\nExample of variable use\nfunction firstFunction(input1, input2)\n{\n var process = input1 + 2;\n var result = process - input2;\n return result;\n}\n\n\nfunction otherFunction(input1, input2)\n{\n var process = input1 + 8;\n var result = process * input2;\n return result;\n}\n\n\nIn 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.\n\nExample of constant with variable\nconst tax = 10;\nconst pi = 3.1415926535;\n\nfunction firstFunction(input1, input2)\n{\n var process = input1 + 2;\n var result = process - input2;\n result = (result * tax)/100;\n return result;\n}\n\n\nfunction otherFunction(input1, input2)\n{\n var process = input1 + 8;\n var result = process * input2 * pi;\n return result;\n}\n\n\nBefore using 'let' in JavaScript we have to add ‘use strict’ on the top of the JavaScript file\n\nExample of let with constant & variable\nconst tax = 10;\nconst pi = 3.1415926535;\nlet trackExecution = '';\n\nfunction firstFunction(input1, input2)\n{\n trackExecution += 'On firstFunction';\n var process = input1 + 2;\n var result = process - input2;\n result = (result * tax)/100;\n return result;\n}\n\n\nfunction otherFunction(input1, input2)\n{\n trackExecution += 'On otherFunction'; # Can add current time\n var process = input1 + 8;\n var result = process * input2 * pi;\n return result;\n}\n\nfirstFunction();\notherFunction();\nconsole.log(trackExecution);\n\n\nIn above example you can track which one function executed when & which one function not used during specific action.\n",
math2001 :

For why to use const, Tibos's answer's great.\nBut you said:\n\nFrom what I can tell, it is used to create immutable variables\n\nThat is wrong. Mutating a variable is different from reassigning:\nvar hello = 'world' // Assigning\nhello = 'bonjour!' // Reassigning\n\nWith const, you can not do that:\nconst hello = 'world'\nhello = 'bonjour!' // Error\n\nBut you can mutate your variable:\nconst marks = [92, 83]\nmarks.push(95)\nconsole.log(marks) // [92, 83, 95] -> the variable has been mutated.\n\nSo, any process that changes the variable's value without using the = sign is mutating the variable.\nNote: += for example is ... reassigning!\nvar a = 5\na += 2 // Is the same as a = a + 2\n\nSo, the bottom line is: const doesn't prevent you from mutating variables; it prevents you from reassigning them.",
T.J. Crowder :

First, three useful things about const (other than the scope improvements it shares with let):\n\n\nIt documents for people reading the code later that the value must not change.\nIt prevents you (or anyone coming after you) from changing the value unless they go back and change the declaration intentionally.\nIt 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.\n\n\nYour questions:\n\n\n When is it appropriate to use const in place of var?\n\n\nYou 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.\n\n\n Should it be used every time a variable which is not going to be re-assigned is declared?\n\n\nThat's up to you / your team.\n\n\n Does it actually make any difference if var is used in place ofconst` or vice-versa?\n\n\nYes:\n\n\nvar 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.\nSee my \"three useful things\" above, they all apply to this question.\n",
janesconference :

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 redeclare them in the code, the program will respectively not change the value or throw an error.\nFor example, compare:\n// Will output 'SECRET'\n\nconst x = 'SECRET'\nif (x = 'ANOTHER_SECRET') { // Warning! Assigning a value variable in an 'if' condition\n console.log (x)\n}\n\nwith:\n// Will output 'ANOTHER_SECRET'\n\nvar y = 'SECRET'\nif (y = 'ANOTHER_SECRET') {\n console.log (y)\n}\n\nor\n// Will throw TypeError: const 'x' has already been declared\n\nconst x = "SECRET"\n\n/* Complex code */\n\nvar x = 0\n\nwith\n// Will reassign y and cause trouble\n\nvar y = "SECRET"\n\n/* Complex code */\n\nvar y = 0\n",
Genovo :

It provides:\n\na constant reference, e.g., const x = [] - the array can be modified, but x can't point to another array; and\n\nblock scoping.\n\n\nconst and let will together replace var in ECMAScript 6/2015. See discussion at JavaScript ES6 Variable Declarations with let and const",
Anthony :

const is not immutable.\n\nFrom the MDN:\n\n\n The const declaration creates a read-only reference to a value. It\n does not mean the value it holds is immutable, just that the variable\n identifier cannot be reassigned.\n",
Tiago Martins Peres :

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).\nWhen 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 hoisting - 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.",
Srikrushna :

var: Declare a variable. Value initialization is optional.\nlet: Declare a local variable with block scope.\nconst: Declare a read-only named constant.\nExample:\nvar a;\na = 1;\na = 2; // Reinitialize possible\nvar a = 3; // Re-declare\nconsole.log(a); // 3\n\nlet b;\nb = 5;\nb = 6; // Reinitialise possible\n// let b = 7; // Redeclare not possible\nconsole.log(b);\n\n// const c;\n// c = 9; // Initialization and declaration at the same place\nconst c = 9;\n// const c = 9; // Redeclare and initialization is not possible\nconsole.log(c); // 9\n// NOTE: Constants can be declared with uppercase or lowercase, but a common\n// convention is to use all-uppercase letters.\n",
Ananda :

'const' is an indication to your code that the identifier will not be reassigned.\nThis is a good article about when to use 'const', 'let' or 'var': JavaScript ES6+: var, let, or const?",