Let and Var Difference JavaScript

Always ready for new things
In javascript, we can define variables in 4 ways

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
varis a function scoped- Declare a variable with
varinside a function that can be used anywhere in the function.

In the above example, var a is function scoped so it can be used anywhere inside the function.
let
letthe keyword is block scoped- Declare variables with the
letkeyword inside the{ }block that can not be accessed from outside that block.

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
varcan be possible to redeclare the same variable name it will not throw an error.

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

3. Hoisting
Hoisting in JavaScript is a behavior in which a function or a variable can be used before declaration.
var
- In
varhoisting is possible. we can use the variable before its declaration.

let
- But In
letdoes not allow us to hoist it will throw an error.


