Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between const and var

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 218
    Comment on it

    Hello Readers! In this blog we will be discussing about the different identifiers. What is the difference between them and when to use which identifier? First lets start with the const.

     

     

    Const : is used to declare a variable whose value cannot be changed after it has been initialized. The value of the variable remains unchanged during re-assignment and also it can not be redeclared.

    1. // define MYVARIABLE1 as a constant and assign value 10 to it
    2.  
    3. const MYVARIABLE1 = 10;
    4.  
    5. // following line will throw an error
    6.  
    7. MYVARIABLE1 = 20;
    8.  
    9. // will print 10 as output
    10.  
    11. console.log( The value of MYVARIABLE1 is: + MYVARIABLE );
    12.  
    13. // redeclaration of a constant will throw an error
    14.  
    15. const MYVARIABLE1 = 20;
    16.  

     

    var : variable declared with the var keywords can be redeclared and re-assigned, that we can change the value of the variable which is declared using the var keyword.

     

    1. var x =10;
    2.  
    3. var y =20;
    4.  
    5. var sum = x+y;
    6.  
    7. console.log(sum); // prints 30 as output
    8.  
    9.  
    10. x= 30; // redeclaration of variable x
    11.  
    12. sum =x+y;
    13.  
    14. console.log(sum); // print 50 as output

     

    Happy Coding :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: