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
var
is a function scoped- Declare a variable with
var
inside 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
let
the keyword is block scoped- Declare variables with the
let
keyword 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
var
can be possible to redeclare the same variable name it will not throw an error.
let
- But in
let
can 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
var
hoisting is possible. we can use the variable before its declaration.
let
- But In
let
does not allow us to hoist it will throw an error.