Var vs Const vs Let featured image

JavaScript first appeared 22 years ago in 1995,  in most of its lifetime there has been only one way to declare a variable using the var keyword.  Some declarations of var can have some unexpected behaviours due to scope. That’s why with the sixth version of JavaScript ECMAScript 2015 developers decided to introduce two new keywords ‘Const’ & ‘Let. In this article, we will run through each and help decide what you should be using in your JavaScript.

Const

‘Const’ is often the best option for declaring variables. ‘Const’ is an abbreviation for constant meaning the variable shouldn’t change.

For example.

 


  const pi = 3.14159;

Download const sample

The ‘const’ declaration stops the variable being overwritten by any stray variables. Meaning you can’t assign pi to another value. We can test this out by using the console window in chrome. Open up the Const Sample by clicking the link above. With the console window type in our constant pi. This will give use our value 3.14159. If we try to change the value of pi we get an error.

 

You should only use a ‘const’ for declaring variables that shouldn’t change. If you expect the value to change each time a script runs eg a score or age, you should use the keyword ‘Let’.

Let

‘Let’ is often the best option for declaring variable were the value is likely to change similar to how var works. The difference being ‘Let’ variables are block-scoped so helps defend against those var scoped errors.  We have a basic ‘Let’ example below.

 


 let score = 0;

Download let sample

In the script, we’re using the score to keep track of the user’s progress in a game. In a typical game as a user plays the score will change. Unlike ‘const’, if you try to reassign the value we can successfully change the score. In the sample below I’ve just added 1 to the score each time showing how the ‘Let’ keyword assigns the new value. You can try it out with the download link above.
This is a rather simple example lets look at a more complex sample where and when you should use ‘Let’ instead of a ‘Const’.

 


   const person = {
     first_name: "Gary",
     job: "Developer"
   }
   
   function personDescription(person) {
     let description = person.first_name;
       if (person.job) {
         description = description + " is a ";
         description = description + person.job;
       }

     console.log(description);

   }

   personDescription(person);

Download let sample two

If we open up the console again we will see ‘Gary is a Developer’.  When the script runs it checks if the person object has a job and if true it will add more information to the end of the description. Let’s see what happens if we change the ‘Let’ keyword to a ‘const’.

 

The console will throw up an error. This happens because we’re are trying to re-assign in the description in the if block. We could change it to ‘var’ and the script would work but unlike var, it has block level scoping which comes in handy in for loops.  For example, using a counter in a for loop can have some unexpected results. Let’s look at another code snippet.

 


     const buttons = document.getElementsByTagName("button");
        for (var i = 0; i < buttons.length; i++) {
            const button = buttons[i];
            button.addEventListener("click", function () {
                alert("Button " + i + " Pressed");
            });
      }

Download let for loop sample

In the example script, we want the button press to give us the number of the button pressed.  When we press the button it will display ‘Button 10 Pressed’. This is because the alert displays the last value of i which means the value has increased by one for every time the loop has run. The issue here relates to var’s scope problem. ‘Var’ lives on a global scope so the value of i is shared between each button. We want each button to have its own self-contained value. By changing ‘var’ to ‘let’ it allows us to do that. So if we run the script again with ‘var’ changed to ‘let’ you should now see each button clicked assigned to its own value, eg pressing button 3 will alert “Button 3 Pressed”.

Summary

‘Const’ is your first option when declaring variables. They help stop reassignment bugs which will help you debug your code faster. Const also has block-level scoping which is everything inside curly braces. ‘Let’ is a great replacement for var when you’re trying to reassign a value. This can be anything from incrementing in a loop, or manipulating strings. The usage of the ‘var’ keyword is not recommended anymore with a number of scoping issues associated with ‘var’. It will save you a lot of developer remorse if you change how you declare your variables using the ‘const’ and ‘let’ keywords.