Constant or const when to use in JavaScript?
According to ES6 specification a constant:
- cannot change through re-assignment
- cannot be re-declared
If we declare an object as constant then we can add properties to that object. Similarly when we declare an array as constant then we can add items to the array list.
In the case of an array or object, we are not re-assigning or re-declaring the constant. The constant is already declared and assigned, we are just adding to the “list” that the constant is pointing to.
Object example
const obj = {}; obj.firstname = 'Joe'; console.log(obj); // {firstname : 'Joe'} obj.lastname = 'Smith'; console.log(obj); // {firstname : 'Joe', lastname: 'Smith'}
Array object example
const arrList = []; arrList.push('Joe'); console.log(arrList); // ['Joe'] arrList.unshift("Smith"); console.log(arrList); // ['Joe', 'Smith'] arrList.pop(); console.log(arrList); // ['Joe']
Not possible with constant
const obj = {}; obj = {firstname: 'Joe'}; // error - re-assigning const arr = ['Jennifer']; const arr = ['Joe']; // error - re-declaring const arrList = 'Joe'; arrList = 'Jennifer'; // error - can not re-assign var arrList = 'Hello'; // error - already declared function arrList() {}; // error - already declared