Blog

What are the differences between var, let and const in JavaScript?

1_lgmSNM4Te_6h_pgUPnec_g

By: Pankaj Madaan, Founder ITCity Solution

In JavaScript, var, let, and const are ways of creating variables. Here, we will talk about the scope and difference between these three ways.

History about variable declaration

In the beginning of JavaScript, there was only one way to declare a variable is using the var keyword. But then let and const came into the picture in ES6 but couldn’t use it right away. Now, all the major browsers are compatible with the let and const syntax, and most of the developers use let and const nowadays in daily life.

What is Var ?

Variables declared using var keyword. This means If they are inside a function we only can access them inside the function scope only and If they are not they are part of the global scope which we can access anywhere. See example below:

In this, Mango is scoped to function scope and Apple belongs to the global scope right. If we try to access a global variable it is possible to do so. but if we try to access a function scoped variable it is not possible. Check this below example:

One of the issues with using the var keyword is they can be redeclared inside the same scope only. This will bring up some issues if we declare another variable using the same name inside the same scope level, the new variable will replace the old one.

And one more issue with var is these variables are not blocked level scoped which means if we have conditions in the statements those are not scoped to that statement but to the entire function or to the global scope level.

What is Let ?

This is the improved version of var declarations in ES6. Variables declaration using this way can eliminate all the issues that we discussed above. let creates variables that are block-level scope. Also, they can not be redeclared and can be updated. This example shows it is the best choice to use let than var.

Check out the below example to understand the behavior of let in the block scope.

What is Const ?

Const variables are cannot be updated or redeclared once we declared. This way is used to declare constants. Same as the let declarations const declarations are block-level scoped. Unlike var and let, If we are using const to declare a variable that needs to be initialized.

I personally prefer to use let and const over var and use const to declare constant variables and always use let to declare variables if it is not a constant.

1 Comment(s)

  1. Nishant saini
    January 18, 2022

    Nice

Comments are closed.