What is up with var, let and const
Tags: javascript, webdev, beginners, hoisting
Published: 2019-12-08 14:34:22

---
title: What is up with var, let and const
published: true
description: What is up with var, let and const? Let's look at the differences and figure out what to use.
tags: JavaScript, WebDev, Beginners, Hoisting
canonical_url: https://vandalen.dev/post/what-is-up-with-var-let-and-const/
---

> Assuming you know some JS basics

Let's start with the 'old' keyword `var` for declaring variables. `var` is top level (aka. global level). Let me show you what that means with an example.

```javascript
function logName(setName){
  if(setName){
    var name = 'Dennis';
    console.log(name);
  } else {
    console.log(name);
  }
}
```
```javascript
logName(true); // 'Dennis'
```

Returns `Dennis` as expected.

```javascript
logName(false); // Undefined (?)
```

Why is this undefined? Shouldn't this return a `ReferenceError`? This is called hoisting. What JavaScript does is, it puts the var at the top level, so to say at the top of your code. You can read it as follows:

```javascript
function logName(setName){
  var name;
  if(setName){
    name = 'Dennis';
    console.log(name);
  } else {
    console.log(name);
  }
}
```

Makes sense now right? If you read it like this it, we expect it to be undefined.

> In JavaScript, a variable can be declared after it has been used.
In other words; a variable can be used before it has been declared.

~ [w3schools](https://www.w3schools.com/js/js_hoisting.asp)

---

So this is where `let` and `const` come in play. 

**let** and **const** are block level. A block is anything between the opening **`{`** and the closing **`}`**

```javascript
function logName(setName){
  if(setName){
    let name = 'Dennis';
    console.log(name);
  } else {
    console.log(name);
  }
}
```
```javascript
logName(true); // 'Dennis'
```

Returns `Dennis` as expected.

```javascript
logName(false); // Uncaught ReferenceError: name is not defined
```

Reference error! This is what we want :) Because we don't expect the variable name to exist at all.

---

## `const` .. vs .. `let`

A `const` can not be reassigned, but is not immutable. You can still alter it, for example: take an array, you can still push and pop, but not reassign to a new array. Let's take a look at what happens. 

### Re-assigning a const:

```javascript
const names = ['Dennis', 'Daan'];

names = ['Harry', 'Faye'];

console.log(names);
```
```javascript
Uncaught TypeError: Assignment to constant variable
```

This doesn't work. We get a type error. We can not reassign a const.

But, only the initial assignment is immutable. We can still change the values of the array.

### Updating the value of a constant:

```javascript
const names = ['Dennis', 'Daan'];

names.push('Harry');
names.push('Faye');

console.log(names);

```
```javascript
(4) ["Dennis", "Daan", "Harry", "Faye"]
```


---

### No more reason to use var?

> If you have been writing correct code, you will probably be able to turn all var statements into let statements without any semantic changes.  
let is preferable because it reduces the scope in which an identifier is visible. It allows us to safely declare variables at the site of first use.  
const is preferable to let. Unless you need to mutate a reference, use a const declaration. This has all the benefits of let along with reducing the presence of uninitialized variables and making code generally easier to reason about. If you aren't sure if you will need to mutate a reference, declare it const until you find yourself explicitly needing to do so.

~ [Aluan Haddad](https://softwareengineering.stackexchange.com/a/323282)

---

## When to use what?

I'm not saying everyone should stick to the following strategy, but this seems to be working for me:

- Default to **const**
- Switch to **let** if you need to change the value
- **var** can be used in the top level. But not that useful, you can also put a let at the top if you want this behaviour.

Oh, and you can use: `Object.freeze()` → if you want it to be immutable.

> This is my first blog! Please let me know if you have feedback :)