Using the const
keyword, you can create variables that cannot change their values (hence they're called constants) once they're initialized, that is, you cannot reinitialize them with another value later in your code.
If you try to reinitialize a const
variable, a read-only exception is thrown. Furthermore, you cannot just declare and not initialize a const
variable. It'll also throw an exception.
For instance, you might want your JavaScript to crash if someone tries to change a particular constant, say pi
, in your calculator. Here's how to achieve that:
const pi = 3.141; pi = 4; // not possible in this universe, or in other terms, // throws Read-only error
The const
variables are block-scoped variables, that is, they follow the same scoping rules as the variables that are declared using the let
keyword. The following example demonstrates the scope of the constant variables:
const a = 12; // accessible globally function myFunction() { console.log(a); const b = 13; // accessible throughout function if(true) { const c = 14; // accessible throughout the "if" statement console.log(b); } console.log(c); } myFunction();
The output of the preceding code is:
12 13 ReferenceError Exception
Here, we can see that constant variables behave in the same way as block-scoped variables when it comes to scoping rules.
When we assign an object to a variable, the reference of the object is what the variable holds and not the object itself. So, when assigning an object to a constant variable, the reference of the object becomes constant to that variable and not to the object itself. Therefore, the object is mutable. Consider this example:
const a = { name: "Mehul" }; console.log(a.name); a.name = "Mohan"; console.log(a.name); a = {}; //throws read-only exception
The output of the preceding code is:
Mehul Mohan <Error thrown>
In this example, the a
variable stores the address (that is, reference) of the object. So the address of the object is the value of the a
variable, and it cannot be changed. But the object is mutable. So when we tried to assign another object to the a
variable, we got an exception as we were trying to change the value of the a
variable.
The difference between const
and let
is that const
makes sure that rebinding will not happen. That means you cannot reinitialize a const
variable, but a let
variable can be reinitialized (but not redeclared).
Within a particular scope, a const
variable always refers to the same object. Because let
can change its value at runtime, there is no guarantee that a let
variable always refers to the same value. Therefore, as a rule of thumb, you can (not strictly) follow these:
- Use
const
by default if you know that you'll not change the value (max performance boost) - Only use
let
if you think reassignment is required/can happen somewhere in your code (modern syntax) - Avoid using
var
(let
does not create global variables when defined in a block scope; this makes it less confusing for you if you come from a C, C++, Java, or any similar background)
Currently, running a benchmark test on my own laptop (MacBook Air, Google Chrome Version 61.0.3163.100 (official build) (64-bit)) produces the following result:
Clearly, performance-wise on Chrome, let
on the global scope is slowest, while let
inside a block is fastest, and so is const
.
First of all, the aforementioned benchmark tests are performed by running a loop 1000 x 30 times and the operation performed in the loop was appending a value to an array. That is, the array starts from [1], then becomes [1,2] in the next iteration, then [1,2,3], and so on.
What do the results mean? One inference we can draw from these results is that let
is slower in a for
loop when used inside the declaration: for(let i=0;i<1000;i++)
.
This is because let
is redeclared every time for each iteration (relate this to the closure section you read earlier), whereas for(var i=0;i<1000;i++)
declares the i
variable for the whole block of code. This makes let
a bit slower when used in a loop definition.
However, when let
is not used inside the loop body but declared outside the loop, it performs quite well. For example:
let myArr = []; for(var i = 0;i<1000;i++) { myArr.append(i); }
This will give you the best results. However, if you're not performing tens of hundreds of iterations, it should not matter.