# Let and Var Difference JavaScript

In javascript, we can define variables in `4 ways`


![variables.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661077012663/T6e5TMCx7.png align="left")

In this article, we talk about the difference between `var` and  `let`.

# Let and Var
In JavaScript, the keywords `var` and `let` are used to declare variables.

The **let** keyword was introduced in 2015 known as `ES6(ES2015)`. And it's the best way to declare variables.

## Why do we have to use the let over the var?


## 1. Scoped

## `var`
- `var` is a function scoped
- Declare a variable with `var` inside a function that can be used anywhere in the function.

![varscoped.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661082064387/VseNUoDw-.png align="left")

In the above example, `var a` is function scoped so it can be used anywhere inside the function.

## `let` 
  - `let` the keyword is block scoped
  - Declare variables with the `let` keyword inside the `{ }` block that can not be accessed from outside that block.


![letscoped.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661082684234/uCsmUTgbe.png align="left")

In the above example, `let a` is declared as a function scoped so it can be accessed from anywhere right? But `let b` is declared as a block-scoped inside the   `if` block statement so it can not be accessed from the outside of the `if` block statement.  

## 2. Redeclare

## `var`
- In `var` can be possible to redeclare the same variable name it will not throw an error.


![redclarevar.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661082925034/o2lfdNU-N.png align="left")

## `let`
- But in `let` can not be possible to redeclare the same variable name it will throw an error.


![redclarelet.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661083071316/NYtLVeQ8k.png align="left")

## 3. Hoisting
**Hoisting** in JavaScript is a behavior in which a function or a variable can be used before declaration. 

## `var`
- In `var` hoisting is possible. we can use the variable before its declaration.

![hoistvar.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661083364357/4TCtTjhw9.png align="left")


## `let`
- But In `let` does not allow us to hoist it will throw an error.

![hoistlet.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661083474601/wV0qtpyoV.png align="left")

