Monday, March 2, 2020

const in JavaScript

The const keyword

JavaScript supported only two scopes Global and Function scope prior to the introduction of let and const. ECMAScript 2015 introduced let and const. The const works very much like let but the reference to the const can not be changed.

There are few important points to keep in mind regarding the const,

  • const cannot be reassigned and a const keyword creates the read the only reference to value. If we have assigned a primitive value to const than it can not be changed.

<script>
  const x=10;
  document.write(x++);//ERROR
//Uncaught TypeError: Assignment to constant variable.
</script>


  • const must be assigned a value at the time of its declaration.

<script>  
  const x; 
  x=15;//ERROR
  //Uncaught SyntaxError: Missing initializer in const declaration
  document.write(x);
</script>


  • const has a block Scope.

<script>      
    {
        const a=12;
        document.write(a+'<br>');
        {
          const a=15;
          document.write(a+'<br>');
          {
            const a=20;
            document.write(a+'<br>');
          }
        }
        document.write(a+'<br>');
      }
</script>
Output:
12
15
20
12

  • The property of a const object can be changed but it cannot be changed to a reference to the new object.

<script>      
         
 // We can change the object
    //before changing the value
    const student={name:'Shankar',roll:15,branch:'CSE'};
   for(item in student)
   {
   document.write('<br>'+student[item]);
   }
   student.roll=20;
//After changing the value
   for(item in student)
   {
   document.write('<br>'+student[item]);
   }
</script>
Output:

Shankar
15
CSE
Shankar
20
CSE

  • The values inside the const array can be changed, we can add new items to const arrays but it should not refer to a new array.

<script>      
    // We can change the content in an array
          const colors = ["RED", "BLUE", "GREEN", "ORANGE"];
          document.write(colors.toString()+'<br>');
            
          colors[2] = "CYAN"; // possible

          document.write(colors.toString());
</script>
Output:
RED,BLUE,GREEN,ORANGE
RED,BLUE,CYAN,ORANGE

  • We can redeclare a const variable inside different block scopes.

<script> 
        {
        const v='something';
        document.write(v+'<br>');
        }
        {
          const v=51;
          document.write(v+'<br>');
        }
         
</script>
 Output:
something
51

  • We cannot hoist a const variable like let.

<script>    
     a = 30;
    document.write(a);
    const a;//ERROR
    //Uncaught SyntaxError: Missing initializer in const declaration
</script>