JavaScript Variable (VAR, LET, CONST) Explained

Hey there! Ready to dive into the wonderful (and sometimes confusing) world of JavaScript variables? If you’ve been coding for a little while, you’ve probably seen var, let, and const sprinkled throughout different code examples.

Each of these keywords creates a variable, but they do so in slightly different ways. Trust me, understanding the distinctions between var, let, and const will save you some headaches down the line, so let’s break it down in a way that’s easy to understand—and yes, with some practical examples too!

JavaScript Variable (VAR, LET, CONST) Explained

1. Let’s Start with var (The Original Variable)

When I first started with JavaScript, var was the only way to declare a variable. It’s the “old-school” way that’s been around since the dawn of JavaScript. While it works, it has some quirks that make it less ideal in modern JavaScript.

Key Things to Know About var:

  • Scope: Variables declared with var are function-scoped, meaning they are accessible anywhere within the function they’re declared in. This can sometimes lead to unexpected issues, especially if you’re used to block-scoped languages.
  • Hoisting: var variables are “hoisted” to the top of their scope. Essentially, you can use a var variable even before you declare it, though this can be confusing if you’re not careful.

Example:

function oldSchoolFunction() {
    if (true) {
        var message = "Hello from var!";
    }
    console.log(message); // This will work because of function scope!
}
oldSchoolFunction(); // Output: Hello from var!

With var, it’s easy to accidentally overwrite variables or have variables “leak” out of loops or conditions. For example, I remember the first time I put var inside a loop and was surprised that it still showed up outside the loop. 😅

2. Meet let (Our Modern Variable Friend)

Then came let, the upgrade we didn’t know we needed! let gives us a lot more control and predictability.

Key Things to Know About let:

  • Scope: let is block-scoped, which means it’s only available within the nearest set of curly braces {} it’s declared in (like loops or conditionals).
  • No Hoisting: Unlike var, let doesn’t hoist in the same way, so you have to declare it before you use it.

Example:

function newSchoolFunction() {
    if (true) {
        let message = "Hello from let!";
        console.log(message); // Works just fine
    }
    // console.log(message); // Error! `message` is out of scope here
}
newSchoolFunction();

Using let is like having a tidy workspace. If you declare a variable with let in a loop or an if block, it stays right there. No surprises! It’s great for making your code more predictable.

I always tell new developers that let is like a security guard for your variables—it keeps them where they belong.

3. Say Hello to const (The Immutable Buddy)

And then we have const. I like to think of const as a “constant” (as the name suggests) because once you declare a variable with const, you can’t reassign it. It’s perfect for values you know won’t change, like configurations or fixed numbers.

Key Things to Know About const:

  • Scope: Like let, const is block-scoped.
  • Immutability: You cannot reassign a const variable once it’s been assigned. But note—const doesn’t make objects or arrays immutable, just the reference to them.

Example:

const PI = 3.14159;
console.log(PI); // 3.14159

// PI = 3.14; // Error! Cannot reassign a constant variable

Example with Objects and Arrays:

const user = { name: "Alice" };
user.name = "Bob"; // This works because we’re modifying the object, not reassigning it
console.log(user); // Output: { name: "Bob" }

// user = { name: "Charlie" }; // Error! We cannot reassign a `const` variable

In the past, I remember trying to use const and then accidentally reassigning it later in my code, which led to some interesting error messages.

After a while, you get used to thinking of const as “set and forget.” It’s perfect for values that should stay put.

When to Use Each One?

Now that you know what each keyword does, here’s a quick guide on when to use each one:

  • var: Honestly, avoid it in most cases. While it has its uses, it can lead to tricky bugs because of its function scope and hoisting behavior.
  • let: Use it when you expect the value of a variable to change, like counters in loops, user input, or state that updates.
  • const: Use it when you don’t plan to change the variable. If a variable shouldn’t be reassigned, const is the way to go!

Personally, I default to const whenever possible. It makes my intentions clear, and it’s a great habit for writing robust code.

Quick Recap

  1. var is function-scoped, hoisted, and can lead to unpredictable code.
  2. let is block-scoped and won’t let you use the variable before it’s declared.
  3. const is also block-scoped and prevents reassignment, which is perfect for constants.

Understanding the differences between var, let, and const can make a huge difference in your code. It’s one of those foundational concepts that, once you’ve got it down, will give you a lot more confidence in structuring your code cleanly and predictably.

Plus, your future self (and anyone else who works with your code) will thank you for writing code that’s organized and easy to follow!

Happy coding, and may your variables stay exactly where you need them! 🎉


Discover more from Prime Inspire

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from Prime Inspire

Subscribe now to keep reading and get access to the full archive.

Continue reading