Var vs let and const; easy as pie
Tags: javascript, es6, beginners, webdev
Published: 2021-01-27 22:00:29

If you've spent any time learning Javascript you've probably seen three ways to declare a variable. This guide will show you an in depth look at the behaviors of 'var', 'let' and 'const'. Afterwards, you'll be setting variables appropriately and confidently.

## For starters...
'Let' and 'const' are apart of ES6 (ECMA script 6). This is the latest approved standardization for Javascript that was released in 2015. ES5 was released in 2011. Modern Javascript frameworks like React and Vue utilize ES6. So it's a great time to jump on board the ES6 bus.

Using 'var', 'let' and 'const' is as easy as this:

```
var pie = 'apple'
let pie = 'apple'
const pie = 'apple'
``` 
## Var-y funny
Let's take a look and see how a 'var' behaves. Var is scoped to the entire function it's in. 

```
function count() {
  for (var i = 0; i < 3; i++) {
    if (true) {
      console.log(i);
    }
  }
  console.log(i);
}
count();

```

![Screen Shot 2021-01-27 at 2.46.22 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1611780396253/bJaTXmFfR.png)
 
Can you see what's wrong in our console?

On line 7, the 2nd console.log(i) is saying i is equal to 3. This is a problem since our for loop should stop when it hit the 3rd loop. Instead of doing that, our 'var' is scoped to the entire count function.

Watch happens when we change our 'var' in our for loop to let:

```
function count() {
  for (let i = 0; i < 3; i++) {
    if (true) {
      console.log(i);
    }
  }
  console.log(i);
}
count();
``` 
![Screen Shot 2021-01-27 at 2.49.01 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1611780560213/9FFFaqYIP.png)
We now get a ReferenceError on the 2nd console.log(i). This is actually what we want. Outside of the for loop, the parent function shouldn't care that we declared a function named i. That's because 'let' is scoped to the code block it lives in. 'Const' is the same way. 'Var' can get tricky since it's scoped to it's function AND it can also collide with variables set in the window. In other words, two variables named the same thing will cause errors in your program.

If you don't know, there is a window object that hosts a ton of behind the scenes stuff. Open up your console on your web browser and type in window to see it all.

![Screen Shot 2021-01-27 at 2.53.10 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1611780799036/aR1TtmbjE.png)

You can imagine we'd get some errors working with larger applications that utilize window if we're using vars everywhere.

So hopefully you can begin to see why it's best practice to stick to setting variables with 'let' and 'const'.

## Let's dig in

As you may have guessed 'let' allows the program to update it's value.

```
let pie = 'apple'
//...
pie = 'pecan'
console.log(pie)
``` 

![Screen Shot 2021-01-27 at 2.56.45 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1611781016847/HGIpvn-GS.png)

Here we declared a variable called pie and set it's value to the string apple. Later on in our app, we updated the pie variable to pecan with no issue. Console logging pie shows us we're set to have pecan pie. Yum!

## I const stop eating...

Let's try the same thing in console with 'const', instead of let.


```
const pie = "apple";
pie = "pecan";
console.log(pie);

``` 
![Screen Shot 2021-01-27 at 2.57.51 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1611781100053/quK0qlPnf.png)

Well no pie for us. That's because we said pie should never update it's value of 'apple' by declaring it with 'const'. And this is a good thing! Our variable is protecting itself against future modification. We all know apple pie is the best pie and should never be replaced. :D

'Const' safe guards your variables by throwing an Uncaught TypeError. 

## Can we scrape 'var' in the trash can?

Why doesn't Javascript just take 'var' out and replace it with 'let'? That's a good question, but the answer is that it would be absolute chaos. Imagine all the websites and apps utilizing 'var' in legacy code. Removing 'var' support would just be such a nightmare for everyone. So, just like mom's giant papier-mâché turkey centerpiece, it stays for the full course meal.

## TL;DR (doggie bag version) 

Let is great to use when you say it's OK for the variable to be updated.

'Const' is great to use when the variable should never update.

'Let' and 'const' are scoped to the code block that they live in.

Using 'var' is like taking a bite out of pie that's been left out for a week. It is scoped to the entire function, regardless of whatever code blocks are in it. So you're probably going to have issues using it and eating old pie.

Get in the habit of using 'let' and 'const'. It will save you some headache in your career as a Javascript developer.

## More dessert please...

What if you wanted to update a variable in a loop (or a code block further into the function)? Piece of cake, just declare the variable at the beginning of the function:

```
function chowDown() {
  let capacity = "empty";
  let inches = 42;
  for (let i = 0; i <= inches; i++) {
    if (i == inches) {
      capacity = "full";
    }
  }
  console.log("my belly is now " + capacity);
}
chowDown();

``` 
![Screen Shot 2021-01-27 at 3.10.28 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1611781832796/S4BDXwn6G.png)

<span>Photo by <a href="https://unsplash.com/@priscilladupreez?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Priscilla Du Preez</a> on <a href="https://unsplash.com/s/photos/apple-pie?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>