Today I wasted an hour debugging a trivial issue, where a local variable named server was being initialized and configured - then, on one of the last lines in the same file, accidentally it was being redeclared, e.g. by another var server = ... statement, effectively creating a new variable named server, thus causing the previous variable to fall out of scope; yet, because these were the same type of variable, with the same name, everything else continued to work, making this fairly hard to debug.
Is there a TypeScript or JavaScript language feature, that prevents this sort of thing?
My thinking is that, declaring two variables with the same name, in the same scope, ought not to be allowed at all.
Perhaps there's a linter or some quality assurance tool that has the ability to check for and prevent this sort of thing? (and perhaps other "bad" patterns?)
Use let everywhere possible.
A let variable cannot be used before its declaration:
var x = 3;
function f() {
console.log(x); // ReferenceError, x is not defined
let x = 5;
}
Two options:
Use ECMA Script 6 and let.
Use jslint with var.
There is a closed issue about this on the GitHub/Microsoft/Typescript page. The recommendation is to target ECMA Script 6 and use let.
ECMA Script 6 with let
In ECMA Script 6 this would create an error:
let x = "foo";
let x = "bar"; // TypeScript with ECMA 6 will complain here
console.log(x);
Duplicate declaration, x
JSLint with var
Also, though the following won't throw a TypeScript error, the jslint tool will complain about it, even if you aren't using strict.
(function () {
var x, y;
x = "foo";
y = "foo";
function sayMsg() {
// jslint will complain here
var y = "bar";
}
sayMsg();
// jslint will also complain here
var x = "bar" + y;
}());
This is what jslint will tell you:
Redefinition of 'y' from line 3.
Combine this with the previous 'var' statement.
I found the following in the MDN
// THIS WILL CAUSE AN ERROR
function f() {};
const f = 5;
// THIS WILL CAUSE AN ERROR ALSO
function f() {
const g = 5;
var g;
//statements
}
But there is no description of proper way to do. So how should I implement?
Quoting from the const's MDN Docs,
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).
Firefox, at least since version 13, throws a TypeError if you redeclare a constant. None of the major browsers produce any notices or errors if you assign another value to a constant. The return value of such an operation is that of the new value assigned, but the reassignment is unsuccessful only in Firefox and Chrome (at least since version 20).
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.
const is not part of ECMA Script 5, so it may not have to supported by all the environments and browsers.
To have the similar behavior, you can see macek's answer.
ECMAScript 5 doesn't really support this. There's a couple tricks you could use though.
You could try something like this
var f = (function() {
var g = 5;
return function() {
return g;
};
})();
Now, every time you run f(), you will also get 5, and it's impossible to change the value of g
Another thing you could do is use Object.defineProperty
var f = {};
Object.defineProperty(f, "g", {
configurable: false,
value: 5
});
f.g; // 5
Even if you try to change the property, f.g will stay set to 5
f.g = 10;
f.g; // 5
If you're working with CommonJS style modules, you sort of get this functionality for "free". Again, g is non-configurable and always guaranteed to be 5.
a.js
var g = 5;
function foo() {
return g;
}
module.exports = foo;
b.js
var a = require("./a");
a(); // 5
I'm wondering what is the difference between let and const in ES6. Both of them are block scoped, as the example in the following code:
const PI = 3.14;
console.log(PI);
PI = 3;
console.log(PI);
const PI = 4;
console.log(PI);
var PI = 5;
console.log(PI);
In ES5 the output will be:
3.14
3.14
3.14
3.14
But in ES6 it will be:
3.14
3
4
5
I'm wondering why ES6 allows the change of const value, the question is why should we use 'const' now? we can use 'let' instead?
Note: jsbin can be used for testing, choose JavaScript to run ES5 code and Traceur to run it with ES6 capabilities.
The difference between let and const is that once you bind a value/object to a variable using const, you can't reassign to that variable. In other words Example:
const something = {};
something = 10; // Error.
let somethingElse = {};
somethingElse = 1000; // This is fine.
The question details claim that this is a change from ES5 — this is actually a misunderstanding. Using const in a browser that only supports ECMAScript 5 will always throw an error. The const statement did not exist in ECMAScript 5. The behaviour in is either JS Bin being misleading as to what type of JavaScript is being run, or it’s a browser bug.
In practice, browsers didn't just go from 0% support for ECMAScript 2015 (ECMAScript 6) to 100% in one go — features are added bit-by-bit until the browser is fully compliant. What JS Bin calls ‘JavaScript’ just means whatever ECMAScript features your browser currently supports — it doesn’t mean ‘ES5’ or ‘ES6’ or anything else. Many browsers supported const and let before they fully supported ES6, but some (like Firefox) treated const like let for some time. It is likely that the question asker’s browser supported let and const but did not implement them correctly.
Secondly, tools like Babel and Traceur do not make ES6 ‘run’ in an older browser — they instead turn ES6 code into ES5 that does approximately the same thing. Traceur is likely turning const statements into var statements, but I doubt it is always enforcing that the semantics of a const statement are exactly replicated in ES5. Using JS Bin to run ES6 using Traceur is not going to give exactly the same results as running ES6 in a fully ES6 specification-compliant browser.
It is important to note that const does not make a value or object immutable.
const myArray = [];
myArray.push(1); // Works fine.
myArray[1] = 2; // Also works fine.
console.log(myArray); // [1, 2]
myArray = [1, 2, 3] // This will throw.
Probably the best way to make an object (shallowly) immutable at the moment is to use Object.freeze() on it. However, this only makes the object itself read-only; the values of the object’s properties can still be mutated.
What you're seeing is just an implementation mistake. According to the ES6 spec wiki on const, const is:
A initialize-once, read-only thereafter binding form is useful and has
precedent in existing implementations, in the form of const
declarations.
It's meant to be read-only, just like it currently is. The ES6 implementation of const in Traceur and Continuum are buggy (they probably just overlooked it)
Here's a Github issue regarding Traceur not implementing const
let
Use block scope in programming.
for every block let create its own new scope which you cannot access in outside of that block.
value can be changed as many times as you want.
let is extremely useful to have for the vast majority of code. It can greatly enhance your code readability and decrease the chance of a programming error.
let abc = 0;
if(true)
abc = 5 //fine
if(true){
let def = 5
}
console.log(def)
const
It allows you to be immutable with variables.
const is a good practice for both readability and maintainability and avoids using magic literals e.g.
// Low readability
if (x > 10) {
}
//Better!
const maxRows = 10;
if (x > maxRows) {
}
const declarations must be initialized
const foo; // ERROR: const declarations must be initialized
A const is block scoped like we saw with let:+
const foo = 123;
if (true) {
const foo = 456; // Allowed as its a new variable limited to this `if` block
}
The let and const
ES6 let allows you to declare a variable that is limited in scope to the block (Local variable). The main difference is that the scope of a var variable is the entire enclosing function:
if (true) {
var foo = 42; // scope globally
}
console.log(foo); // 42
The let Scope
if (true) {
let foo = 42; // scoped in block
}
console.log(foo); // ReferenceError: foo is not defined
Using var in function scope is the same as using let:
function bar() {
var foo = 42; // scoped in function
}
console.log(foo); // ReferenceError: foo is not defined
The let keyword attaches the variable declaration to the scope of whatever block it is contained in.
Declaration Order
Another difference between let and var is the declaration/initialization order. Accessing a variable declared by let earlier than its declaration causes a ReferenceError.
console.log(a); // undefined
console.log(b); // ReferenceError: b is not defined
var a = 1;
let b = 2;
Using const
On the other hand, using ES6 const is much like using the let, but once a value is assigned, it cannot be changed. Use const as an immutable value to prevent the variable from accidentally re-assigned:
const num = 42;
try {
num = 99;
} catch(err) {
console.log(err);
// TypeError: invalid assignment to const `number'
}
num; // 42
Use const to assign variables that are constant in real life (e.g. freezing temperature). JavaScript const is not about making unchangeable values, it has nothing to do with the value, const is to prevent re-assigning another value to the variable and make the variable as read-only. However, values can be always changed:
const arr = [0, 1, 2];
arr[3] = 3; // [0, 1, 2, 3]
To prevent value change, use Object.freeze():
let arr = Object.freeze([0, 1, 2]);
arr[0] = 5;
arr; // [0, 1, 2]
Using let With For Loop
A particular case where let is really shines, is in the header of for loop:
for (let i = 0; i <= 5; i++) {
console.log(i);
}
// 0 1 2 3 4 5
console.log(i); // ReferenceError, great! i is not global
Summary:
Both the let and the const keyword are ways to declare block scoped variables. There is one big difference though:
Variables declared with let can be reassigned.
Variables declared with const have to be initialized when declared and can't be reassigned.
If you try to reassign variables with declared with the const keyword you will get the following error (chrome devtools):
Why should we use this?
If we know that we want to assign a variable once and that we don't want to reassign the variable, using the const keywords offers the following advantages:
We communicate in our code that we don't want to reassign the variable. This way if other programmmers look to your code (or even you to your own code you wrote a while ago) you know that the variables which are declared with const should not be reassigned. This way our code becomes more declarative and easier to work with.
We force the principle of not being able to reassign a variable (JS engine throws error). This way if you accidentally try to reassign a variable which is not meant to be reassigned you can detect this at an earlier stage (because it's logged to the console).
Caveat:
Although a variable declared with const can't be reassigned this doesn't mean that an assigned object isn't mutable. For example:
const obj = {prop1: 1}
// we can still mutate the object assigned to the
// variable declared with the const keyword
obj.prop1 = 10;
obj.prop2 = 2;
console.log(obj);
If you also want your object to be non mutable you can use Object.freeze() in order to achieve this.
let and const
Variables declared with let and const eliminate specific issue of hoisting because they’re scoped to the block, not to the function.
If a variable is declared using let or const inside a block of code (denoted by curly braces { }), then the variable is stuck in what is known as the temporal dead zone until the variable’s declaration is processed. This behavior prevents variables from being accessed only until after they’ve been declared.
Rules for using let and const
let and const also have some other interesting properties.
Variables declared with let can be reassigned, but can’t be
redeclared in the same scope.
Variables declared with const must be assigned an initial value, but
can’t be redeclared in the same scope, and can’t be reassigned.
Use cases
The big question is when should you use let and const? The general rule of thumb is as follows:
use let when you plan to reassign new values to a variable, and
use const when you don’t plan on reassigning new values to a
variable.
Since const is the strictest way to declare a variable, it is suggest that you always declare variables with const because it'll make your code easier to reason about since you know the identifiers won't change throughout the lifetime of your program. If you find that you need to update a variable or change it, then go back and switch it from const to let.
var declarations are globally scoped or function scoped while let and
const are block scoped.
var variables can be updated and re-declared within its scope; let
variables can be updated but not re-declared;const variables can neither be updated nor re-declared.
They are all hoisted to the top of their scope. But while var
variables are initialized with undefined, let and const variables are
not initialized.
While var and let can be declared without being initialized, const
must be initialized during declaration.
Here are some notes that I took that helped me on this subject. Also comparing const and let to var.
Here's about var:
// Var
// 1. var is hoisted to the top of the function, regardless of block
// 2. var can be defined as last line and will be hoisted to top of code block
// 3. for undefined var //output error is 'undefined' and code continues executing
// 4. trying to execute function with undefined variable
// Example: // log(myName); // output: ReferenceError: myName is not defined and code stops executing
Here's about let and const:
// Let and Const
// 1. use `const` to declare variables which won't change
// 2. `const` is used to initialize-once, read-only thereafter
// 3. use `let` to declare variables which will change
// 4. `let` or `const` are scoped to the "block", not the function
// 5. trying to change value of const and then console.logging result will give error
// const ANSWER = 42;
// ANSWER = 3.14159;
// console.log(ANSWER);
// Error statement will be "TypeError: Assignment to constant variable." and code will stop executing
// 6. `let` won't allow reference before definition
// function letTest2 () {
// log(b);
// let b = 3;}
// Error statement will be "ReferenceError: b is not defined." and code will stop executing
Var
The var keyword was introduced with JavaScript.
It has global scope.
It can be declared globally and can be accessed globally.
Variable declared with var keyword can be re-declared and updated in the same scope.
Example:
function varGreeter(){
var a = 10;
var a = 20; //a is replaced
console.log(a);
}
varGreeter();
It is hoisted.
Example:
{
console.log(c); // undefined.
//Due to hoisting
var c = 2;
}
Let
The let keyword was added in ES6 (ES 2015) version of JavaScript.
It is limited to block scope.
It can be declared globally but cannot be accessed globally.
Variable declared with let keyword can be updated but not re-declared.
Example:
function varGreeter(){
let a = 10;
let a = 20; //SyntaxError:
//Identifier 'a' has already been declared
console.log(a);
}
varGreeter();
It is not hoisted.
Example:
{
console.log(b); // ReferenceError:
//b is not defined
let b = 3;
}
Global object property
var no1 = "123"; // globally scoped
let no2 = "789"; // globally scoped
console.log(window.no1); // 123
console.log(window.no2); // undefined
Redeclaration:
'use strict';
var name= "Keshav";
var name= "Keshav Gera"; // No problem, 'name' is replaced.
let surname= "Rahul Kumar";
let surname= "Rahul Khan "; // SyntaxError: Identifier 'surname' has already been declared
Hoisting
function run() {
console.log(name); // undefined
var name= "Keshav";
console.log(name); // Keshav
}
run();
function checkHoisting() {
console.log(name); // ReferenceError
let name= "Keshav";
console.log(name); // Keshav
}
checkHoisting();
Note: in case of var, you will get undefined, in case of let you will get reference error
Const
It allows you to be immutable with variables.
Const declarations must be initialized
const name; // ERROR: const declarations must be initialized
A const is block scoped like we saw with let:+
const num = 10;
if (true) {
const num = 20; // Allowed as its a new variable limited to this `if` block
}
/*
// declaration of const in same block scope is not allowed
const a = 10;
const a = 15; //Redeclaration of const a Error
console.log(`const outer value `+a);
*/
/*
//declaration of const in different block scope is allowed
const a = 10;
console.log(`outer value of a `+a)
{
const a = 15; //Redeclaration of const allowed in different block scope
console.log(`ineer value of a `+a);
}
*/
/*
// re assigning const variable in any block scope is not allowed
const a = 10;
a = 15; //invalid assignment to const 'a'
{
a = 15; //invalid assignment to const 'a'
}
*/
/*
// let also can not be re declared in the same block scope
let a = 10;
let a = 15; //SyntaxError: redeclaration of let a
*/
/*
// let can be redeclared in different block scope
let a = 10;
{
let a = 15; //allowed.
}
*/
/*
// let can be re assigned in same block or different block
let a = 10;
a = 15; //allowed for let but for const its not allowed.
*/
/*
let a = 10;
{
a = 15; //allowed
}
*/
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?
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.
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.
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 ... reassigning!
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 reassigning them.
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.
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 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.
var: Declare a variable. Value initialization is optional.
let: Declare a local variable with block scope.
const: Declare a read-only named constant.
Example:
var a;
a = 1;
a = 2; // Reinitialize possible
var a = 3; // Re-declare
console.log(a); // 3
let b;
b = 5;
b = 6; // Reinitialise possible
// let b = 7; // Redeclare not possible
console.log(b);
// const c;
// c = 9; // Initialization and declaration at the same place
const c = 9;
// const c = 9; // Redeclare 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.
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 assume 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.
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 trying to make another variable called x, and this would be a more accurate test:
const x = 'const';
x = 'not-const';
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.
Summary:
const creates an immutable binding, meaning a const variable identifier is not reassignable.
const a = "value1";
You cannot reassign it with
a = "value2";
However, 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.
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 reassignment 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 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.
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.
The main point is that how to decide which one identifier should be used during development.
In JavaScript here are three identifiers.
var (Can redeclared and reinitialize)
const (Can't redeclared and reinitialize, and can update array values by using push)
let (can reinitialize, but can't redeclare)
'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.
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 JavaScript we have to add ‘use strict’ on the top of the JavaScript 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.
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.
It provides:
a constant reference, e.g., 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 ECMAScript 6/2015. See discussion at JavaScript ES6 Variable Declarations with let and const
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 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.
'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': JavaScript ES6+: var, let, or const?
I am not an expert in the JavaScript compiling business, but it makes sense to say, that V8 makes use of the const flag.
Normally 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.
If 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.
It can also save the proper operations for that datatypes since the type will not change.
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?!?