The Startup
Published in

The Startup

The Story of VAR vs LET vs CONST

(The answers to confusions)

Hello there, do you know the most popular programming language of 2020 according to Stackoverflow? Ok, I will give you a hint. Which language was top on popularity last year? You guessed it right. Yes, it is the “Javascript”. Stackoverflow does a survey every year since 2011(from 2013 they compare popularity among programming languages) and when it comes to the popularity of programming languages, Javascript has a tremendous record being top. But today we are not here to talk about the popularity of javascript, rather than we will focus on a very common topic of confusion among the newbie devs about javascript. And that is the difference between var vs let vs const.

We all are familiar with variables right? The most common part that every programming language used to have. Like other programming languages, you can declare variables in javascript too.

declaring a variable in javascript

As simple as you can see. And as you can see you don’t need to declare the variable type during variable declaration, which is a great thing as you don’t have to cast your type in case you want to change the type. Whenever you want to assign something else to the same variable just override it.

Even you can assign a whole function to a variable and it will work, no big deal. Everything was going right, but there came a few confusions with the var keyword. Its behavior varies between scopes. So what is a scope? The scope is nothing but a block of code where you restrict the area of your code to execute. How is that?

understanding the use of a scope

As you can see here, we have defined a few variables with the same name. The first one declared at the first line, the second one at line 4 and finally the third one at line no 12. And as you can see we did our first log in line 8 which is printing “Jane Doe” in the console. Why is that? It's supposed to print “John Doe” right? But look carefully we declared again a variable at line 4 with the help var keyword. That’s why when logging, it’s looking at its immediate block/scope which is from lines 3 to 6. It found a variable with name person that’s why it’s printing “Jane Doe” instead of “John Doe”.

What if we did not declare any new variable? It would then logged out “John Doe” as it didn’t find any variable with the name ‘person’ at its block/scope. As it didn’t find, it would look down to its parent scope and if found there it would have printed that. In case the parent scope didn’t have any variable naming ‘person’ it will keep looking to their parent scopes and will print undefined or through a reference error in case no variable found with that name. So, here we used two terms.

  1. Current/Local Scope
  2. Parent/Global Scope

Current/Local scope is the block of code that has a certain area of execution. Like line number 3 to 6 has its own meaning or own logic to be executed. So variables declared in that area will be treated as a local variable of that scope. And variables declaring outside the local scopes are known as global scope variables(like the first line declaration and line 12 as they do not have any parent scope).

Coming back to the point, what if the person was not redeclared ‘person’ in the logPerson() method? The simple answer is it will look for the parent scope like we did in logAnotherPerson() method. The logAnotherPerson() method doesn’t have its local variable naming ‘person’. So it looked for its parent scope. There it found a variable named ‘person’ with a value ‘Alex’ on it. So it consoled that out. It introduces us to the concept of ‘hoisting’.

Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function). Of note however, is the fact that the hoisting mechanism only moves the declaration. The assignments are left in place. Functions declarations are also hoisted, but these go to the very top, so will sit above all of the variable declarations. You can go through this article to get more details on hoisting.

Life is very easy, right? But wait a second. Did you notice we have declared the variable ‘person’ three times including global and local scope? Is that a good practice to declare a variable with the same name in the same scope? I mean there is a huge chance to get the value overridden by another unintentionally. Shouldn’t be we stopped? There comes the concept of let.

Why let?

So far we have used the var keyword to declare a variable, so why need another way to declare them. Short answer to this question to maintain block scope. The varaible declared with var declared are available outside their scope where variable declared with let are restricted to their scope. Let’s see a quick example.

{
var x = 2;
}
// x CAN be used here

Before ES2015 JavaScript did not have Block Scope. Variables declared with the let keyword can have block scope. Variables declared inside a block {} cannot be accessed from outside the block:

{
let x = 2;
}
// x can NOT be used here

Again, redeclaring a variable using the var keyword can impose problems. Redeclaring a variable inside a block will also redeclare the variable outside the block:

var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2

As you can see, this results in unexpected behaviour. You might want to use your local and global variables for differenct purposes. But the varaible get overriden by the block scope variable which can be embarrassing in some part of your code. Redeclaring a variable using the let keyword can solve this problem. Redeclaring a variable inside a block will not redeclare the variable outside the block:

var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10

Moreover, the var keyword allow you to redeclare variable with the same name in the same scope. Which might not a good practice as if your code are long enough you might end up with declaring variable with the same name couple of times or may be more. Even if you work on a team, your team members might get confused about the actual behaviour of the variable. This problem can be solved using let too. If you declare a variable with let it will through an error on runtime and if your IDE has ES6 plugins installed you will be notified during typing.

Let’s wrap up use of let with another last example. The behaviour of let and var not only varies between scopes and hoisting but also varies in loops. Before we move on lets see an example of var ‘s behaviour in loop:

var i = 5;
for (var i = 0; i < 10; i++) {
// some statements
}
// Here i is 10

As you can see, the variable declared in the loop redeclares the variable outside the loop. On the other hand the let keeps it’s value unchanges outside the loop in case it was declared earlier.

let i = 5;
for (let i = 0; i < 10; i++) {
// some statements
}
// Here i is 5

So here, let is keeping your loop block different from outside block. So use them carefully.

Ok, done with let vs var , but what about const? Let’s explore..

Why const?

The const keyword is similar to let but this force you not to re-assign value to the declared variable. You can refer this to the ‘constant’. The values or variables you don’t want to be changed should be declared with the keyword const . It behaves same as the let does, meaning that the scopes and hoisting behaviour is same as let , so rather than describing that part again we will focus on the difference between them.

As I said earlier, variables declared with const can’t be re-assigned. But it can be extented. What kind of extension? You can change any value of a key or push a new key to a object declared with const. Even you can overrite the value of that key. It acts same for the arrays too. You can push a new value to the array or change value of any key. Let’s see an example for better understanding:

// You can create a const object:
const car = {type:”Fiat”, model:”500", color:”white”};

// Trying to re-assign value:
car = {type:”Volvo”, model:”EX60", color:”red”}; // ERROR

// You can change a property:
car.color = “red”;

// You can add a property:
car.owner = “Johnson”;

Here, we have declared a variable with the const keyword named car. It has three properties. When you try to replace or re-assign a new object you’re getting error, but when you access them with there property and try to change them you are good to go. It works in the same way for arrays:

// You can create a constant array:
const cars = [“Saab”, “Volvo”, “BMW”];

// You can change an element:
cars[0] = “Toyota”;

// You can add an element:
cars.push(“Audi”);

So how this work? I mean as const are not re-assignable but the value are getting changed. This is because you declare variables with const it points or referes to a memory allocation/address. You can not put/replace something new to that address. But you can extend it. By extending the reference doesn’t change. So you are using the same reference with modifying the value of it.

So var vs let vs const?

Use let where you need to maintain scopes or where you want values to be re-assigned. Where you don’t want to re-assign, go for const. let are useful for loops and block statements where const can be used for global scopes and good to declare objects. Use var where you need function scope. But after the release of ES6 the use of var came to very low.

Thanks for staying with me. Clap for me if you like it and feel free to share.

--

--

--

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +756K followers.

Recommended from Medium

JavaScript Tutorial

Build a full stack Express GraphQL API with GraphQL Designer in a few minutes.

Twitter Application

Parse Integer from a String ?

How to easily add Nested RecyclerView

cleaning up redundant javascript 2

React Tutorial for Beginners

Floating Point Error

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
Mehedi Hassan Sunny

Mehedi Hassan Sunny

A software engineer from Bangladesh.

More from Medium

My house runs Redux

Do not pollute your app root

My config folder

Online tool generate typescript interface for you

sample

null vs. undefined: Can I use only one?