loading...

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

bipinrajbhar profile image Bipin Rajbhar ・2 min read

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.

Posted on Apr 8 by:

bipinrajbhar profile

Bipin Rajbhar

@bipinrajbhar

I love to share every thing that i have learned

Discussion

markdown guide