DEV Community

Bipin Rajbhar
Bipin Rajbhar

Posted on

What is the difference between var, let and const in JavaScript?

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 = "🍎"; 
Enter fullscreen mode Exit fullscreen mode

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 = "πŸ‡"; 
Enter fullscreen mode Exit fullscreen mode

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(); 
Enter fullscreen mode Exit fullscreen mode

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)