Understanding the JavaScript keywords - var, let & const

Subscribe to my newsletter and never miss my upcoming articles

If you have been programming with JavaScript or a newbie to JavaScript, you may have come across keywords like var, let, and const in your code, or while perusing code snippets.

Do you know the difference between these keywords and which one to appropriately use ? If you're not sure of which one to use at different instances, you are at the right place. Let's discuss about each keyword in-depth.

var

Prior to the birth of ECMAScript 6 (ES2015), var was the only way to declare variables and constants in JavaScript. To understand var, we need to first understand how they are scoped in a function from the example below.

Function Scope

 function counter() {
   for (var i = 0; i < 4; i++) {
      console.log(i);
   }
   console.log(i);  // 4
 }
counter();

From the above code snippets, we have a variable i that is declared inside the for-loop. The console output for the code snippets above will be:

/* Output */
   0
   1
   2
   3
   4

What is important to note from the above code snippet is that i is declared inside the for-loop, it is still accessible outside the scope of the for-loop. The reason being that var variables are accessible within the scope of the function that they are declared and can be leaked into the window scope or into a parent/base scope.

One would expect that the scope of i should be limited to the block within which it is declared but from the above example, i is accessible everywhere within the counter() function. This behavior is peculiar to JavaScript var keyword. Let's look at another example.

   var name = 'Sheygs';

A variable name is declared using var in a global scope as seen from the example above. JavaScript treats this as a global variable, and attaches it to the window object. It is generally not a good practice to attach global variables to the window object because there is only one instance of the window object.

Let's say you were using a third-party library that has variables with the same name as your global variables, the likelihood of your variables being overridden is high.

var variables have function scope if declared inside a function; otherwise they have a global scope.

Because var does not offer block-scope and as a result, leads to an unexpected behavior of your application, JavaScript introduced the let and const keywords to overcome the drawbacks faced with var.

let

If we declare a variable inside a for-loop block of code, we want it to be scoped within that block and be inaccessible outside of it. This behavior is achieved using the let keyword. From our very first example, let's replace let with `var.

  function counter() {
    for (let i = 0; i < 4; i++) {
      console.log(i);
    }
      console.log(i);  
  }
counter();

The output of this example after replacement of var with let will be slightly different from our very first example.

  /* Output */
  0
  1
  2
  3
  Uncaught ReferenceError: i is not defined

The console.log outside of the for-loop returns an error. It returns an undefined i as it doesn't know its value. This is an expected behavior we get using the let keyword as opposed to var.

let variables are blocked-scope. Variables declared within a block of code cannot be accessed outside of it.

const

const is very similar to let as both keywords are blocked-scope. However, the difference being that const cannot be assigned or re-defined. Take a look at the example below to understand the key difference between them.

  let name = 'Sheygs';
  name = 'Billions';
  console.log(name); // Output: Billions

In the example above, I have assigned a name using let. You noticed here that I re-assigned another value to name and it works. In the same example switching let for const, will throw an Uncaught TypeError.

 const name = 'Sheygs';
 name = 'Billions';
 console.log(name); // Uncaught TypeError

The above example will throw an Uncaught TypeError: Assignment to a constant variable.

The key point to note here is that, const does not allow you to re-assign values to a const variable whereas reassignment of a value using let works just fine.

const with objects

Let's look at how const objects work in JavaScript.

  const bioData = { 
    name: 'Sheygs',
    age: 21
  }
  // can mutate object properties
  bioData.name = 'Billions';

  // Uncaught TypeError: Assignment to a constant variable
  bioData = {
      name: 'Billions',
      age: 21
  }

From our example above, we can only have object properties mutated using the const keyword. However, we cannot re-assign the entire object.

Recap

var - Can be re-assigned, re-defined and has a function scope. When declared outside of a function, it has a global scope and attaches itself to the window object.

let -  Can be re-assigned; its scope is within a block of code.

const - Cannot be re-assigned or re-defined. Its scope is within a block of code. (Unlike true immutable datatypes such as those produced by Immutable.js and Mori, a const object can have properties mutated.)

If you like this post, please like and share.

No Comments Yet