var vs let vs const in Javascript

What is basically a variable?

I am not going discuss al the complicated stuff of how your data is stored at memory level and how they are seperated and arranged down deep but I am going to actually share with you the reason why there actually exists three different variable types in js.

const

What does const actually mean? , Yes it simply means it is a constant straight away and what do we use it for well obviously to store constants which can be modified after declaration.

const sample = "I am const";

But there is only one restriction here with const, i.e, you must initialize the variable as soon as you declare it or else an gets thrown on to your screen.

let

One of the wonderful things about js is every keyword it has is so meaningful and serves it's use case well, the same applies for let. It is a variable declaration which is used to store variable values. So literally you can think of it as letting a certain value into variable taking and then letting another value again till your purpose is served.

let a="I am Deadpool";
a="I am batman ๐Ÿฆ‡";
// and so on

And if we see all modern js projects we will see only let and const in them as var is an old and not suggestable variable declaration type but still you can find var in some old or legacy javascript projects, Now let's see why should we not use var.

var

if(true){
var a=5;
console.log(++a);
}
console.log(a);

Now let's have a look at this above code block where we have a variable called "a" located inside an if block and generally if you are familiar with this block scope from any other languages you might have by now understood that this a variable is invisible outside the curly braces but this is where var let's you down you can even access a outside the scope and not just that if you have more than one version of same named variable in different scopes then the last version of the value in code file is taken, So at the very end SIMPLY DON'T USE VAR!

So by now I hope you got a brief understanding of how to use let and const and why not to use var at all in js, Catch you in the next one ๐Ÿ‘‹.

1
Subscribe to my newsletter

Read articles from Balaji Chennupati directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Balaji Chennupati
Balaji Chennupati

Passionate about web dev, java and devops, crafting solutions one line of code at a time.