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.
const
in place of var
?var
is used in place of
const
or vice-versa?This question is related to
javascript
node.js
constants
immutability
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:
a constant reference, eg const x = []
- the array can be modified, but x
can't point to another array; and
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.
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.
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.
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
" objectsFor 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.
var
and let
are a good matchlet
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 const
rict 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. ecmascript-6 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
):
Your questions:
When is it appropriate to use
const
in place ofvar
?
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 of
const` 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.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.
Source: Stackoverflow.com