Background:
let is a successor of var keyword with imposed restrictions. These restrictions make the chances of making fewer mistakes and with added security. Basically, it has block scope i.e. it is only available to the block where it is declared. In other words, variables cannot be accessed outside the block it has been declared.
const accessibility is also inside block scope. But once initialized cannot be re-initialized. This can be tricky in the case of Array, Objects
What does array initialization mean?
let arr = [1, 2, 3, 4, 5];
arr
contains the reference (address or pointer) of the first element of the array. That is the reason why this never holds good.
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [1, 2, 3, 4, 5];
if (arr1 == arr2)
console.log("Both arr1 and arr2 are same");
This shall never print Both arr1 and arr2 are same
in the console. Though they looks same in all aspects. But if we see then arr1
and arr2
are pointing to different locations in the memory. The same concept goes with objects. For example:
let obj1 = {name:'John', age:'22'}
let obj2 = {name:'John', age:'22'}
if (obj1 == obj2)
console.log("Both obj1 and obj2 are same");
obj1
and obj2
are pointing to different memory locations. So the console.log statement shall never run.
If we use const
declaration for the array or object, then according to the definition it cannot be re-initialized. But actually the identifier assigned to the array or object is a memory pointer (address). The array or object can be modified (mutated) accordingly.
Answer to the question:
const util = require('util')
This type of declaration makes sure that accidentally util
is not declared the second time. This makes the code less error-prone i.e. reduce the chances of making mistakes. const
declaration in function makes it less error-prone. As redeclaring, it throws an error.
For instance, say there is a function you declared factorial
that is responsible for finding factorial of a number. Let us consider this example:
const factorial = (n) => {
let fact = 1;
for(let i=1;i<=n;i++)
fact *= i;
return fact;
}
const factorial = 5;
console.log(factorial(10));
Here it will throw an error. const
makes the use of the identifier factorial unique. i.e. a function that takes an input and finds factorial of it.
This helps in making lesser mistakes that are very difficult to debug.
If an array or object is declared const
, then the array or object can be modified (mutated) but any other identifier cannot use the same name that is declared using const
.
I hope this helps.