JavaScriptReact

let vs var vs const - Difference between let, var and const in javascript

author image

Cloudaffle

Team

2nd Jan, 2021   |   1190 Words   |   8 Min Read

With javascript, variable declarations have always been one of its tricky parts. Unlike most C-based languages, javascript variables are always not created at the spot where you declare them. Where a variable is created usually depends on how you declare it. Apart from declaring a variable using the var keyword, ECMAScript 6 enabled developers to create variables using the let and the const keywords. Let's deep dive into a quick comparison between let vs. var vs. const keywords and derive some best practices of declaring a javascript variable based on their individual properties. We will also try to answer whether a let is better than var or const is better than let?

The ECMA in ECMAScript 6 stands for “European Computer Manufacturer’s Association” and it’s a body that is responsible for developing and laying down the specifications for newer versions of ECMAScript. Javascript, in turn, is a scripting language that complies with ECMAScript standards.

var Declarations and Hoisting

Variable declarations using the var keyword undergo a specific mechanism of variables declaration called hoisting. Hoisting is a mechanism via which variable declarations are moved to the top of their scope before code execution. So a variable defined somewhere within the function would be created at the top of the function. Also, if the variable is declared outside the function it attaches itself to the global scope. To better understand what hoisting does, let’s look at the following function for demonstration.

function setColor(condition){
    if (condition) {
        var color = 'blue';
        return color;
    } else {
        return null;     
    } 
}

Now, if you are new to javascript and unfamiliar with the concept of hoisting, you would expect the variable color to be created only when the condition evaluates to true. But this is not the case. The below code will give you a clear idea of how javascript is reading your code and exactly the variable color being created.

function setColor(condition) {
  // Due to hoisting the variable is created at the top of the block scope
  var color;

if (condition) {
    // Variable is assigned a value over here 
    var color = 'blue';
    return color;
  } else {
    // Variable color exists here as well with a value of undefined 
    return null;
  }
  // Variable color exists here as well with a value of undefined 
}

let vs. var Declarations and Lexical Scopes

Lexical scoped or block scopes are variable declarations without the hoisting mechanism and make the declared variables inaccessible outside the defined scope. Only with the release of ECMAScript 6 (ES6) that let keywords to declare variables were introduced, bringing in block-level variable bindings that other C-Type languages have. If you compare var vs. let, block-level binding is one of the major differences between the two. The syntax of declaring a variable using the let keyword is the same as using the var keyword. Let’s look at the following code example to understand what difference a block-level binding creates while declaring a variable using the let keyword.

function setColor(condition) {
  if (condition) {
    // Variable is created and assigned a value over here  
    let color = 'blue';
    return color;
    // variable color is only avaiable in scope of this condition
  } else {
    // Variable color does not exist here  
    return null;
  }
  // Variable color does not exist here  
}

The above example of the setColor() function behaves much like any other C-Type language.

No Redeclaration In The Same Scope Using let Keyword.

Unlike the var keyword, which lets you declare the same variable again within the same scope, the variable declared with the let keyword will throw an error. With the let keyword, only a single variable with the same identifier can be created in the existing scope even if the declaration has been made using the var keyword. Let’s have a look at the following piece of code as an example.

var color = 'blue'; 
// Declaring the same variable with let keyword will not work 
let color = 'red'// throws error 

If the same variable is declared in a different scope, it will not throw an error but will be available to be used with a different value within the scope it has been declared. Here is an example:

if (condition) {     
  // This will not throw error      
  let color = 'red';      
  // color will be available as red in this scope   
}

Declaring variables using the const keyword

With the introduction of ECMAScript 6 const, a keyword to declare a constant was introduced. Javascript constants work almost similarly to most C-Type languages. A constant is a variable, the value of which does not change once it has been declared. For this very reason, every constant must be initialized upon declaration as well. Unlike the variables declared with the var and let keywords, the const keyword's variable needs to be initialized at the declaration. Consider the following code example:

// Valid Constant 
const favouriteColor = 'blue'

// Syntax error if constant is not initialized 
const color;

Here the favouriteColor constant will be declared successfully because it has been initialized at the time of the declaration. However, the color constant will throw an error because it has not been initialized at the declaration.

const vs. let Declarations

const like let declarations have a block-level scope. Unlike the variables declared using the var keywords, constants are not hoisted to the top of the scope within which they are declared.

function setColor(condition) {
    if (condition) {
        // Constant is created and assigned a value over here  
        const color = 'blue';
        // Constant color is only avaiable in scope of this condition
    } else {
        // Constant color does not exist here  
        return null;
    }
    // Constant color does not exist here  
}

If you consider the above example, the constant color is only declared and initialized if the condition is true and remains within the conditional scope.

How const is different from let and var

Despite its similarities with let keyword, there is one major point of differentiation between constants declared with const and variables declared with let and var keywords. Unlike variables, the value of a constant does not change. Any attempt to reassign the value of a constant again will throw an error. Consider the following code as an example:

const color = 'blue';

// Trying to re-assign the value will throw an error
color = 'red'

In a nutshell, a constant in javascript behaves much as it would in other C-Type languages wherein the value that is assigned to a constant remains constant and does not change.

However, it is important to note that if the value the constant holds is an object, the object values can be modified. This is how javascript constants are different from other C-Type languages.

So is let Better Than var?

Having seen the above examples and understanding how three keywords are different from each other, we would only conclude that each of the ways of declaring a variable is unique and would serve a particular use case. For most of the declaring instances, the let keyword would be most suitable, but var and const would have their relevant use cases. All three would serve specific purposes while writing your code based on what is actually needed to be achieved.

What Are Your Thoughts About "let vs var vs const - Difference between let, var and const in javascript". Comment To Let Me Know.

I tried to cover all aspects of "let vs var vs const - Difference between let, var and const in javascript" and I would love to have a discussion and know your thoughts on the article. Feel free to post your feedback in the comments below and improve upon what we have over here. Happy Commenting 🙂 !