Coding Ninjas Logo

Home > JavaScript Questions > What are the different ways to define a variable in JavaScript? And when to pick which one to use?

What are the different ways to define a variable in JavaScript? And when to pick which one to use?


Answer:

There are three possible ways of defining a variable in JavaScript(ES6/2015):

  1. Var – The var keyword is used to declare a variable and, optionally, initialize the value of that variable globally.
    Example:

        var userName = "rajat";
    
        // username can be used here
    
        function myFunction() {
            // userName can also be used here
        }
    

  2. Let – Introduced in ES2015. The let keyword is used to define a variable that will be used only in the block it is defined in. Usually provides a hint that the variable may have been reassigned, i.e. a counter in a loop, or a value swap in an algo.
    The let provide Block{} Scope variables. Hence, it can't be accessed outside the scope. Example:

        {
            let a = 2;
        }
        // a can NOT be used here
        
    

  3. Const – Introduced in ES2015. Declaring a variable with const is similar to that of let when it comes to Block Scope, i.e not accessible outside the block variables. The const variable must be assigned a value when they are declared. For example:
    Incorrect Way

        const PI;
        PI = 3.14159265359;
    

    Correct Way
        const PI = 3.14159265359;
    

    The const variables cannot be reassigned
        const PI = 3.141592653589793;
        PI = 3.14;  // This will give an error
        PI = PI + 10;  // This will also give an error
    


Similar Questions