Hello, everyone π, I hope you are doing great π.
So, today you are going to learn what is the difference between var
, let
, and const
? in this article.
In ES5, you can declare a variable via var
. The variable created with the var has function scoped. It means that you cannot access the variable outside the function.
// function scoped
var apple = "π";
var keyword
- function scope
- Can be initialized during or after the variable declaration
- Can be reassigned
- Can be redeclared
In ES6, you can declare a variable via var
, let
, and const
. The variable created with the let
or const
is block-scoped. It means that you can not access the variable outside the block.
// block-scoped
let banana = "π";
// block-scoped
const grapes = "π";
let keyword
- block scope
- Can be initialized during or after the variable declaration
- Can be reassigned
- Can not be redeclared
const keyword
- block scope
- must be initialized during variable declaration
- Can be reassigned
- Can not be redeclared
Example
function displayFruit() {
if(true){
// function-scoped
var apple = "π";
// block-scoped
let banana = "π";
// block-scoped
const grapes = "π";
}
console.log(apple); // "π";
console.log(banana); // ReferenceError: banana is not defined
console.log(grapes); // ReferenceError: grapes is not defined
}
fruit();
Pro Tips
- Use
const
when you do not want what to reassign a variable. - Use
let
when you want what to reassign a variable. - Avoid using
var
.
Now, you know what is the difference between var
, let
, and const
? π€.
Thanks for reading! My name is Bipin Rajbhar; I love helping people to learn new skills π. You can follow me on Twitter if youβd like to be notified about new articles and resources.
Top comments (0)