Difference between let, var and const in Javascript

Written by manik | Published 2020/04/12
Tech Story Tags: javascript | javascript-development | javascript-utility | javascript-fundamentals | understanding-javascript | ecmascript-6 | programming | beginners | web-monetization

TLDR ECMA in ECMAScript 6 stands for the European Computer Manufacturer’s Association. Javascript is a scripting language that complies with ECMA standards. The variable declarations using the var keyword undergo a mechanism of variables declaration called hoisting. Unlike most of the C-based languages, javascript variables are always not created at the spot where you declare them. 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 done using var.via the TL;DR App

With javascript, variable declarations have always been one of its tricky parts. Unlike most of the 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 as well. Lets deep dive into a quick comparison between 
let
 vs 
var
 vs 
const
 keywords and derive some best practices of declaring a variable in javascript based on their individual properties. We will also try to answer the question of whether 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 get a better understanding of what hoisting does, let’s have a 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 where exactly is 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. It is only with the release of ECMAScript 6 (ES6) that let keyword to declare variables was introduced which brought in block-level variable bindings which 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 have a look at the following code example to understand what difference does 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 Re-declarations 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 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 done 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 

Now 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:

var color = 'blue';

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

Declaring variables using const keyword

With the introduction of ECMAScript 6 const a keyword to declare a constant was introduced. Javascript constants work almost similarly to the 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 variable declared with the const keyword need to be initialized at the time of 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 time of declaration.

const vs let Declarations

const like let declarations have a block-level scope. This means 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 available is only declared and initialized if the condition is true and remains within is the scope of the conditional itself.

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 re-assign 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.
The Above can be explained with the following code example:
// Declare a person constant which is an object 
const person = {
  name: 'John',
  age: 18
}

// Change the age property 
person.age = 20;

console.log(person)

// This is how the output will look like 
/**
{
  name: 'John',
  age: 20
}
**/

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. While for most of the instances of a declaring the let keyword would be most suitable, but var and const would have their relevant use cases as well. All three of them would serve specific purposes while you are writing your code based on what is actually needed to be achieved.
Previously published at https://cloudaffle.com/post/let-vs-var-vs-const

Written by manik | 🤯 My Brain Keeps Talking, Always 📙 Love To Learn New Tech 👨🏼‍🏫 Passionate About Teaching 🤓 Nerd For Sure
Published by HackerNoon on 2020/04/12