Still, confused? ‘var’ or ‘let’ in Javascript

Tags: variables, javascript, es6, declarations
Published: 2020-08-30 12:03:36

Are you still thinking about whether to use var or let in javascript? Let me show you a comparison chart of why let makes more sense and how you could avoid potential issues by making use of let.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/azfnbg7tu4hd6hzkcapl.png)

> I developed android applications before switching to web development using Nodejs Javascript. In android, we declared variables using primitive data types like int, float, char, etc. but javascript is very different, it just uses ‘var’ declaration. So cool, right?

But as Javascript evolved, there were some potential issues popping up which needed some modifications in the current way of development. Following comparison helps you to save your valuable time in developing some more cool features instead of fixing and resolving issues.

**Comparison 1: Origin and Definition**

**Var:** It is there since Javascript is originated. Mainly used for declaration i.e. initialization and assignment.

**Let:** ES2015 or (ES6) introduced two new ways to declare variables i.e. using let and const.

Let is used for variable declaration i.e. initialization and assignment.

Const is used for variable declaration too but its value once assigned cannot be changed (it is immutable) e.g. mathematical pi. If you attempt to change the value of const then it will throw an error

-----------------------------------

**Comparison 2: Variable Scope**

**Var:** It is function- scoped. Let’s understand what does it mean to be function scoped by the below example.
```
console.log(x);
var x= 'Hello World';
console.log(x);

Output

undefined
Hello World

```

**Explanation**

If variables are declared inside a function, they will not be available to the parent function, but vice-versa is true. That means all parent declared variables are accessible by the child function. As you see above, there was no error while executing the first line i.e. console.log(x), as the compiler understood variable x is defined in the code. But since its value is initialized at a later stage, it will display undefined at first.

> This can be a potential source for a lot of bugs

**Let:** It is a block-scoped. Let’s understand what does it mean to be block scoped by the same example but replacing *var* with *let*

```
console.log(x);
let x= 'Hello World';
console.log(x);

Output 
ReferenceError: x is not defined
```
**Explanation**

Why does this happen? let does not hoist variable declaration. New term hoisting, I will explain in detail below. But in short, it means its existence starts only when it is declared not before it and also lives within this block. So if you try to use this variable in any other function without declaring it will throw an error.

This behavior is also referred to as **Temporal Dead Zone**

> This means using let you can write less error-prone codes. You can declare variables inside blocks (if statements, for loops, functions, and so on) without worrying about overwriting some previously declared variable.

-----------------------------------

**Comparison 3: Redeclaring**
Let us understand with help of below code

**Var:**
```
var a;
var a; // Works fine. It overrides previous declaration

```
**Let:**
```
let a;
let a; // SyntaxError: Identifier 'a' has already been declared

---------------

const PI_VALUE = 3.14;
PI_VALUE = 7.89; // TypeError: Assignment to constant
```

-----------------------------------
**Comparison 4: Variable Hoisting**

Let us understand with the help of our previous code

**Var:**
```
console.log(a);
var a = 'Hello World';

Output 
undefined

```
Why??? We should have expected output to be ‘Hello World’, right? Let me break it down a bit. Let’s see how the compiler will read this code.

```
var a;
console.log(a);
a = 'Hello World';

```
As you see above, the compiler internally moved all variable declaration on top, and leave the value to be assigned at the step where we want it. Hence, we don’t see any error but also no value. Variables are initialized with default value as undefined when they are created. So if you try to print a var after initialization, its value will be undefined.

> During compile-time, JavaScript only stores function and variable declarations in the memory, not their actual value.

**Let:**

```
console.log(a);
let a = 'Hello World';


Output 
ReferenceError: a is not defined
```
All declarations (function, var, let, const, and class) are hoisted in JavaScript, while the var declarations are initialized with undefined, but let and const declarations remain uninitialized.

> let variables will only get initialized during runtime by the JavaScript engine.

-----------------------------------

**Comparison 5: Closures**

Let us understand this with the help of below code

**Var:
```
for (var i = 0; i < 3; i++) {
     setTimeout(() => console.log(i), 0);
}

Output
3
3
3

```
Is this what you expected? No right? This is because of hoisting. It executed the for loop and passes the last value of i to the inner function

**Let:**
```
for (let i = 0; i < 3; i++) {
      setTimeout(() => console.log(i), 0);
}

Output
0
1
2
```
Here, in this case on each iteration, it will get a new variable instance.

-----------------------------------

**Comparison 6: Miscellaneous**

**Var:**

* No error is thrown if you declare the same variable twice using var. The values will be overridden with the latest assignment. (though “strict mode” in es5 takes care of that too).
* Only reason var still exists is because of backward-compatibility. Since there are many browsers still not supporting ES2015.

**Let:**
* let and const will throw an error if a variable is declared twice
* Most Javascript experts agree var shouldn’t be used.
* Linters are now pointing out the usage of var as bad coding practice. ESlint can be configured with a “no-var” rule that throws an error if there is any var being used.
* let is preferable to var because it reduces the scope in which an identifier is visible. It allows us to safely declare variables at the site of first use.
* Not all browsers support ES6 specification, we might need to use the tool: Babel which will help transpile code from ES6 to ES5.

### Do you still find yourself using var? What’s stopping you from switching over to using let? Share your experiences below in the comment section ###