Difference Between Var ,Let and Const variable in JavaScript

Difference Between Var ,Let and Const variable in JavaScript

Learn Each in Simplified manner with Examples

ยท

2 min read

Table of contents

Hello everyone, hope you are all doing well. My name is Surya L, and the aim of this blog is to teach you all about Difference Between Var ,Let and Const variable in JavaScript.

There are 3 types of Variable declaration.

  • Var

  • Let

  • Const

Var:

  • The var keyword declares a variable globally, or locally if it is declared inside a function.

  • var is function scoped because once declared it can be used throughout the function.

  • Example:

    var numArray = [];
    for (var i = 0; i < 3; i++) {
    numArray.push(i);
    }
    console.log(numArray);
    console.log(i);
    
  • The Output of above code is ๐Ÿ‘‡

[0, 1, 2]

  • The value of var variable can be changed through out the function for example:

    var a=5;
    a=7;
    console.log(a);
    
  • First the value 5 will be assigned to variable a. Then a is assigned with the new value 7.

  • var is an ECMAScript1 feature.

  • Supported browsers are -: Chrome , Internet Explorer, Microsoft Edge, Firefox, safari , opera

Let:

  • Let is a block scoped variable.

  • Whenever a let variable is declared, it is limited to the block of code in where it is declared.

  • let is a feature of ES6 or ECMAScrpit2015.

  • Supported browsers are -: Chrome49, Microsoft Edge12, firefox44 , safari11, opera36.

  • Once declared the value of the let variable cannot be changed unlike var variable. For example:

    let a=5;
    let a=6;
    console.log(a);
    

    When this code is run we get the error SyntaxError: Identifier 'a' has already been declared.

Const:

  • Const variable is also introduced in ES6 or ECMAScrpit2015.

  • Once the value of the Const variable is determined, it cannot be changed and we would get a error when we try to change the value.

  • For example:

    const a=8;
    console.log(a);
    

    The Output of above code is ๐Ÿ‘‡

8

  • If we try to change the value of Const variable we get error Assignment to constant variable in the console.

  • For example:

    const a=8;
    a=9;
    console.log(a);
    

    Conclusion:

  • var is function scoped because once declared it can be used throughout the function.

  • Whenever a let variable is declared, it is limited to the block of code in where it is declared.

  • Once the value of the Const variable is determined, it cannot be changed and we would get a error when we try to change the value.

Thanks for reading the blog. Do let me know what you think about it.

You can connect me with Showwcase Twitter Blog GitHub Contact Me

Did you find this article valuable?

Support Surya's Web Blogs by becoming a sponsor. Any amount is appreciated!

ย