Difference between Var, Let & Const

In the beginning, we only had the var keyword for declaring a variable in JavaScript. But after the introduction of ES6 in 2015, two new keywords were introduced — let and const.

But why was there a need for let and const to be introduced for the same reason we had var? We will discuss this and also the differences between them in this article with examples.

VAR

Before going into more detail, how about understanding the word scope first as it will be used many times, and we need to understand it for declaring variables too.

Scope

Let’s understand this with the help of an example -

It is of three types -

  • Functional Scope
  • Global Scope
  • Block Scope

Functional Scope

Global Scope

Any variable declared inside a function without any of the keywords is also considered a global variable.

Block Scope

Let’s see an example to understand them -

Functional Scope

The above example contains a variable i declared with the keyword var and has been declared inside a function making its scope functional. Thus, it can be accessed from both inside and outside of the ‘for loop’ but within the braces of function.

Block Scope

While in this above example, i is declared with let making it a variable with block scope. Because of this, it is not accessible outside of the curly braces.

A set of parenthesis also falls in the block scope category, but when attached with curly braces like in this case.

Scope of VAR

Hoisting in Var

console.log (greeter);var greeter = “say hello”

it is interpreted like this:

var greeter;console.log(greeter); // greeter is undefinedgreeter = “say hello”

In the case of var, variable declarations can be made anywhere and can be accessed from anywhere within its scope. This is because variables declared with var without any value are considered undefined.

Problems with var

Check the below example -

Problem of var

let

Scope of let

let is Block Scoped

Hoisting in let

Advantages of let over var

Why not see an example to get a clear picture -

let can’t be re-declared

Const

Scope of Const

Hoisting of Const

Advantages of Const

It means that in const -

  • A constant value cannot be re-assigned
  • A constant array can not be re-assigned
  • A constant object cannot be re-assigned

But we can -

  • Change the elements of a constant array
  • Change the properties of a constant object

How about an example to understand this better -

Conclusion

Difference between the three

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ateev Duggal

I am a front-end developer from India with over one year of experience in freelancing with skills like Git, HTML5, CSS3, Bootstrap 4&5, and React.