DEV Community

Bipin Rajbhar
Bipin Rajbhar

Posted on

13 6

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay