Javascript var, let, and const: the differences

Javascript var, let, and const: the differences

Javascript variables are names given to data storage locations in Javascript. Before 2015, variables have always been declared with the var keyword, like this:

var  name = "Mus3ab";

But since 2015, when the ECMAScript 6 (es6) version of javascript was released, two new keywords for variable declaration, the let and const keywords, came with it.

let age = 13;
const key = "abc123";

Why was Var replaced?

Var has some drawbacks that can lead to bugs in Javascript code, which led to the introduction of let and const.

The var keyword has three drawbacks, which are

  • Variables declared with the var keyword are function-scoped

  • Variables declared with the var keyword can be redeclared

    JavaScript does not allow developers to redeclare a variable previously declared in a block. But the var keyword allows it.

      var name = "Mus3ab";
      var name = "David";
    
  • The var keyword allows hoisting.

    Hoisting in Javascript is when a variable is assigned a value before it is declared.

      number = 40;
      var number;
      console.log(number);
    

How do the let and const keywords address these?

Despite the similarities between the let and const keywords, there is a difference: the value of variables declared with the let keyword can be reassigned, while that of const cannot.

let number = 40;
number = 45;

const key = "abc123";

To fix the drawbacks of the var keyword, the let and const keyword has these attributes:

  • They are block-scope.

    Any variable declared with a let or const keyword can only be accessed within their block.

      if (x == 0) {
        let y = 1;
        const z = 2;
      }
    

    The variables y and z above can only be accessed within the if block.

  • Variables declared with let and const cannot be redeclared.

      let name = "David";
      name = "ken";
    
      const age = 16;
    
  • They do not support hoisting.

    You have to declare your variables before assigning values to them.

      let name;
      const school;
    
      name = "Ken";
      school = "Havard";
    

And that is all for now:

Now that you have read about the var, let, and const keywords, I hope you will start using the let and const keywords in your Javascript code to avoid bugs.

Remember to like this article if you found it interesting, and drop your comment if you feel that there is a part of this article you want to add to or correct.

Keep learning, keep growing.