Skip to main content

How to use 'const' keyword in JavaScript?

const is one of 3-keywords you can use to declare variables. There are 2-other keywords – let and var. All 3-keywords declare variables, but they’re slightly different from each other.

Const in JavaScript

The const keyword was introduced in ES6 to allow create a block scope variables, same as let. In JavaScript, const does not mean constant, it means one-time assignment.

It allow to create an immutable and mutable variables. Immutable variables means, variables whose values cannot be modified(change) in programming are known as immutable, while values that can be changed are known as mutable.

# Declaring JavaScript Const Variables:

Syntax :

Let’s see the syntax of const keyword :

 ➤ Syntax :

<script>
    const variable_name = value;
</script>
Parameter :
  • const : JavaScript reserved keyword.

  • var_name : Name of constant variable

  • value : Required, Initializing constant value.

Note : A variable declared with const must be initialized.

# immutable and mutable variable in const

It does't define a constant value. It defines a constant reference to a value. Because of this, we can't change constant primitive values, but we can change the properties of constant objects or array.

Let's see an example of immutable variable in const :

 ➤ Example 1 : Immutable variable;

<script>
    const x=25; 
    x++; //ERROR, not allowed
    x= 20;//ERROR, not allowed
    x= x+5; //ERROR, not allowed
</script>

Let's see an example of mutable variable in const :

 ➤ Example 2 : Mutable variable;

<script>
    //You can create a const object
    const student = {name:"Ankaj", branch:"CS"};

    //You can change a property
    student.name = "Ankaj Gupta";  //Allow

    //You can add a property
    student.rollno = "45"; //Allow
</script>

# Scope of const keyword :

1.) Global scope :

  • Using const keyword to define variable globally. Once you define globally, and access anywhere inside your code.

 ➤ Example : Variable scope globally;

<script type="application/javascript; version=1.7">
    const x=1; //'x' is gloabal variable;
     console.log("Start program :",x);
    function display()
     {
        if(true)
         {
          console.log("Inside block :",x); //x visible 
         }
         console.log("Inside function :",x); //x visible
     }
     display(); //calling JavaScript function
     console.log("End program :",x); //x visible
</script>

2.) Local scope :

  • Using const keyword to define variable locally (local scope). It can't be accessed outside the function declaration.

 ➤ Example : Variable scope within function;

<script type="application/javascript; version=1.7">
   function display()
     {
       const a =10;
       console.log("Inside function : "+a); //Inside function :10
     }
     display();
    //ReferenceError: a is not defined
     console.log("outside function : "+a);
</script>

3.) Block scope :

  • Variables declared with const keyword inside a block { } , can't be accessed from outside the block. When you try to access from outside of block, It will get a ReferenceError.

 ➤ Example : variable scope within block;

<script type="application/javascript; version=1.7">
  const age = 22;
  if (age > 21)
    {
      const message ="Hello";
      console.log("Inside block, message : ",message); //Hello!
    }
    //ReferenceError: message is not defined
    console.log("Outside block : ",message);
</script>

# Variable Hoisting :

Variable defined with ‘const’ keyword are not hoisted to the top. So if you try to accessed the variable before declaration it, javascript throw a Reference Error.

Note : Because you can not re-assign a const, you know it is not possible to hoist them.

Let's try to create an exaple :

 ➤ Example : Variable hoisting with const;

    Variables declared with const are not hoisted to the top.

<script>
    console.log(name); //ReferenceError
    const name = "Ankaj";
</script>

 ➤ Read more :

Read more about Variable Hoisting : Click Me


Important point's of const keyword in JavaScript :

  • Assigned when Declared : The const variable must be both declared and initialised. If you don't assign variables value at declaration time, It will give the SyntaxError.

 ➤ Syntax :

<script>
    const constant_name = value;
</script>

 ➤ Example Incorrect : Variable declared without initialization;

    You need to initialize it with a value when declaring otherwise will have the SyntaxError.

<script>
    const name;  //SyntaxError: Missing initializer in const declaration
</script>

 ➤ Example correct : Variable declared with initialization;

<script>
    const name= "Ankaj";
</script>
  • Block-scope : Variables declared with const keyword inside a block { } , can't be accessed from outside the block. When you try to access from outside of block, It will get a ReferenceError.

 ➤ Example :

    Variables declared with the const keyword have Block Scope.

<script>
    if(true)
    {
      const a=10;
      document.write(a); //Outpt : 10
    }
    document.write(a); //ReferenceError: a is not defined
</script>
  • Variable Re-declaration : Unlike var, Constant variable can't declare the same variable more than one time using ‘const’ keyword within the same scope. When we try to redefine, It will get a SyntaxError.

 ➤ Example : variable re-declaration in same scope;

    Re-declaring a variable with const, in same scope is allowed.

<script>
    const a = 10; 
    const a = 20; //SyntaxError: Identifier 'a' has already been declared
</script>

 ➤ Example : variable re-declaration in another scope;

    Re-declaring a variable with const, in another scope not allowed.

<script>
    const a = 10; //Global scope
    function display()
    {
      const a= 20; //Local scope
    }
    if(true)
    {
      const a= 25; //Block scope
      display();
    }
</script>
  • Variable value re-assigned : Variables declared with var or let can be changed later in the program. Once a const variable is initialized, its value can never be changed again, and it can’t be reassigned to a different value.

 ➤ Example : Re-assigned a new value;

    The code will throw an error when we try to re-assign the existing const variable.

<script>
    // Assign value to x variable
    const x=10;
    //Reassign variable with a new value
    x = 20; //TypeError: Assignment to constant variable.
</script>
  • Dynamic type : As you known, const variables can not be re-assign, that's why variables declared with const keyword are not dynamic type.

 ➤ Example : Dynamic type variables;

<script>
    consr myName = 'Ankaj Gupta';  //Ankaj Gupta
    myName= 100; //Error
    myName= true; //Error
</script>

# How to change const values in javascript ?

  • As you known, Variable declare with const keyword you can not change later in program, but this condition is apply only for constant primitive values not for constant object or array.

  • If you declare constant object or array value with const keyword, You can change or add the properties of const variables.

Let's see the examples :

 ➤ Example i : constant primitive values;

    If we assign a primitive value to a constant, we can't change the primitive value.

<script>
    const x=25; 
    x++; //ERROR, not allowed
    x= 20;//ERROR, not allowed
    x= x+5; //ERROR, not allowed
</script>

 ➤ Example ii : constant objects values;

    You can change the properties of a constant object.

<script>
    //You can create a const object
    const student = {name:"Ankaj", branch:"CS"};

    //You can change a property
    student.name = "Ankaj Gupta";  //Allow

    //You can add a property
    student.rollno = "45"; //Allow

    //Note : But you can't re-assign a constant object.
    student = {name:"Anmol", branch:"ECE"};  //ERROR, not allowed
</script>

 ➤ Example iii : constant array values;

    You can change the elements of a constant array.

<script>
    //You can create a constant array.
    const student = ["Name", "Branch", "Rollno"];

    //You can change an element.
    student[2] = "Enroll_No"; //Allow

    //You can add an element.
    student.push("Gender"); //Allow

    //Note : But you can't reassign a constant array.
    student = ["Name", "Branch", "Enroll_No", "Gender"];  //ERROR, not allowed
</script>

Comments

Popular Posts

Django static files not working when debug false || debug true

# Django static and media files not working when debug is false In this article you will learn how to fix problem of not loading static files and media in Django even the DEBUG is FALSE. This is the easiest and safest solution. # Problem: Django static and media files not working when debug is false  ➤ Code: settings.py DEBUG = False #True ALLOWED_HOSTS = [ '*' ] #Host name # Problem Fix: Let's see, How you can fix the problem of Django static and media files not working when DEBUB = False : 1.)First way: devserver in insecure mode If you still need to server static locally ( e.g. for testing without debug ) you can run devserver in insecure mode: python manage.py runserver --insecure --insecure: it means you can run serve

java program for student details using inheritance

# Java program to print student details using "single-level" inheritance In this section, You will learn how to print student details using single inheritance in java, with Scanner and without Scanner class. 1.) With " Scanner " class Let's try to create a simple example :   ➤ Example : student.java; import java.util.Scanner; class StudentDetails {    int roll_no ;    String name , cl ; //creating a function to take student details    void input () { Scanner sc = new Scanner ( System . in );   System . out . print ( "Ente

How to remove the date and .html from every blogger post url

#Remove date and .html from blogger post url A Common search term which every blogger search is How to Remove Date From Blogger Post URL or how do I remove date from blogger permalink? Follow the steps below and then date and .html will be removed from the URL of your blogger post. Step 1 : Login to your Blogger blog and select Theme / Template. Step 2 : Click on Edit HTML and paste the below code just above the </head> tag let's see code :   ➤ Code : mycode.js; Copy code <script type='text/javascript' > //<![CDATA[ // BloggerJS v0.3.1 var urlTotal,nextPageToken,postsDatePrefix=!1,accessOnly=!1,useApiV3=!1,apiKey="",blogId="",postsOrPages=["pages","posts"],jsonIndex=1,secondRequest=!0,feedPriority=0,amp="&"[0];function urlVal(){var e=window.location.pathname,t=e.length;return