Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

JavaScript Const

JavaScript constants are variables, whose values cannot be modified after initialization. We declare them using the keyword const. They are block-scoped just like the let keyword. Their value cannot be changed neither they can be redeclared. Const keyword is part of the es2015 (es6) specification of the javascript.

Declaring a const

We declare constants using the keyword const keyword

Example:

         
 const MaxAllowed=100 ;
    
        
    

The initial value is a must

The initial value of the const must be specified along with the declaration.

         
const maxValue=100;     //Ok
 
const maxValue1;        //Uncaught SyntaxError: Missing initializer in const declaration
    
        
    

Const is block-scoped

The const is similar to the let keyword. They are local to the code block in which we declare them.

         
const Rate = 10;       //global scope
 
if (true) {
  const Rate = 8;     //its scope is limited to the if block
  console.log(Rate);  //Prints 8
}
 
console.log(Rate);    //Prints 10
    
        
    

We cannot modify its value

We can assign a value to the const variable at the time of declaration. Once initialized, we cannot modify its value. So if you try to assign a new value to a constant it results in an error.

         
const MaxTry=10 ;
MaxTry=5;            //Uncaught TypeError: Assignment to constant variable.
    
        
    

Similarly, if the const is an object.

         
const emp = { id:1, name:"Rahul"}
emp = {id:2, name:"Sachin"}      //code1.js:2 Uncaught TypeError: Assignment to constant variable.
    
        
    

Const and object

You cannot assign new content to a const variable. But if the content is an object, then we can modify the object itself.

The following example throws the error Assignment to constant variable when we try to assign a new object to obj variable.

         
const obj= {
    firstName: "Allie",
    lastName: "Grater"
};
 
obj = { firstName: "Jack",
        lastName: "Ferguson"
      }
 
//Uncaught TypeError: Assignment to constant variable.
    
        
    

However, you can change the properties of the object itself.

         
const obj = {
    firstName: "Allie",
    lastName: "Grater"
};
 
 
obj.firstName= "Jack",
obj.lastName= "Ferguson"
    
        
    

To understand why you need to understand the difference between value types & reference types

There are two types of data types in JavaScript. One is value types (primitive values) & the other one is reference types. The types string, number, Bigint, boolean, undefined, symbol, and null are value types. Everything else is reference types. The primary difference between value types & Reference types is how JavaScript stores them in memory.

         
const num=10
 
const obj= {
    firstName: "Allie",
    lastName: "Grater"
};
 
    
        
    

JavaScript stores the value types in the variable itself. But in the case of reference type variables, they do not store the value. But they store the reference to the memory location where JavaScript stores the actual values.

Useful References

Both the code below throws Uncaught TypeError: Assignment to constant variable error as we are assigning a new value.

         
num  = 20;        
const obj  = {    firstName: "Jack",     lastName: "Ferguson" };  
    
        
    

But you can change the object itself.

         
obj.firstName= "Jack",
obj.lastName= "Ferguson"  
    
        
    

The following is an example using arrays.

         
const cities =['Delhi','Mumbai','Chennai']
 
//not allowed. You cannot assign a new array
cities= ['New york','London','Sydney']       //Error here
 
 
//But you can change the items of the array.
cities.splice(0,3);                        //allowed
cities.push('New york','London','Sydney')  //allowed
console.log(cities);  
    
        
    

Cannot access before the declaration

Accessing the const before the initialization results in a ReferenceError. The variable in a “temporal dead zone” from the start of the block until the initialization. You can read more about it from Hoisting in JavaScript.

         
console.log(City);     //Uncaught ReferenceError: Cannot access 'City' before initialization
const City  = "DELHI"; 
    
        
    

Cannot Redeclare a const.

Trying to redeclare constant throws the following error. Uncaught SyntaxError: Identifier ‘MaxTry’ has already been declared”.

         
const MaxTry=10;
console.log(MaxTry);
 
const MaxTry=100;   //Uncaught SyntaxError: Identifier 'MaxTry' has already been declared
                     
console.log(MaxTry); 
    
        
    

Summary

You can use const to declare values that do not change. Use let for everything else. But always remember the fact that if const points to an object, then you can change its properties.

Read More

  1. JavaScript Tutorial
  2. Data Types in JavaScript
  3. JavaScript String
  4. Template Strings & String Interpolation
  5. Tagged Templates
  6. String to Number
  7. Number Data Type
  8. NaN in JavaScript
  9. Min, Max & Safe Values
  10. EPSILON & Floating Point Precision
  11. Infinity
  12. BigInt
  13. BintInt Vs Number
  14. Boolean Data Type
  15. Undefined
  16. null
  17. null vs undefined