Understanding Variables in JavaScript: The Var, Let, and Const Adventure!
Tags: webdev, javascript, beginners, programming
Published: 2023-08-21 05:08:15

Welcome, fellow JavaScript enthusiasts!

Today, we embark on an epic journey to unravel the mysteries of variables in JavaScript. Variables are essential tools that help us store and manipulate data. In this blog post, we’ll dive into the three amigos of JavaScript variables: var, let, and const. 🎉

## **🌟 Meet the Trio: var, let, and const 🌟**

**1. var:**

- Ah, var, the OG of JavaScript variables!
- In the early days, var was all we had.
- It’s still in use today, but its quirks and unpredictability have made way for the more reliable let and const.

Let’s see an example to understand var’s behaviour:

```jsx
var name = "John";
function greet() {
  if (true) {
    var name = "Jane";
    console.log("Hello, " + name + "!");
  }
  console.log("Goodbye, " + name + "!");
}
greet();
```

Output:

```
Hello, Jane!
Goodbye, Jane!
```

Wait, what just happened? 😱

- Despite the name variable being declared inside the if block, var has a function-level scope.
- This means the variable is accessible both inside and outside the block.

**2. let:**

- Now, let’s introduce the new kid on the block: let!
- It brought more predictability and block-level scoping to the table.
- With let, we can limit a variable’s accessibility to the block it’s defined in.

Take a look at the following example:

```jsx
function countdown() {
  for (let i = 3; i >= 0; i--) {
    setTimeout(function () {
      console.log(i === 0 ? "Blast Off!" : i);
    }, (3 - i) * 1000);
  }
}
countdown();
```

Output:

```
3
2
1
Blast Off!
```

- The let keyword allows us to create a new variable `i` for each iteration of the loop.
- As a result, the setTimeout function captures the correct value of `i` for each iteration, giving us the desired countdown effect.

**3. const:**

- Finally, we have const, short for “constant.”
- As the name suggests, a variable declared with const cannot be reassigned once it’s been assigned a value.
- This immutability makes const perfect for values that should remain constant throughout the program.

Let’s see an example to understand const better:

```jsx
const pi = 3.14159;
pi = 3.14; // Oops! We can't do that.
console.log(pi);
```

Output:

```
TypeError: Assignment to constant variable.
```

- As you can see, attempting to reassign a value to a constant variable results in a TypeError.
- So, choose const when you want to make sure a variable retains its initial value throughout the program.

## **🌐 Scoping: Where Art Thou, Variable? 🌐**

1. **var’s Scope:**
- As we saw earlier, var has function-level scope.
- It means that a variable declared with var is accessible throughout the entire function, regardless of where it’s declared.
- Let’s have another example:

```jsx
function printNumbers() {
  for (var i = 1; i <= 5; i++) {
    setTimeout(function () {
      console.log(i);
    }, i * 1000);
  }
}
printNumbers();
```

Output:

```
6
6
6
6
6
```

Oh no! Why did it print all sixes? 😭

- The issue here is that the setTimeout function runs after the loop has completed, and by that time, the value of i is already 6.
- All the setTimeout functions access the same variable, resulting in unexpected output, and by that time, the value of `i` is already 6.
- All the setTimeout functions access the same variable, resulting in unexpected output.

**2. let’s Block Scope:**

- Now, let’s bring in the hero of the day: **let**!
- With **let**, we can achieve block-level scoping, making our lives easier. Let’s modify the previous example:

```jsx
function printNumbers() {
  for (let i = 1; i <= 5; i++) {
    setTimeout(function () {
      console.log(i);
    }, i * 1000);
  }
}
printNumbers();
```

Output:

```
1
2
3
4
5
```

Voila!

- This time, each setTimeout function captures the value of `i` for its corresponding iteration, thanks to let's block-level scoping.
- We get the expected output, showcasing the power of let.

**3. const’s Immutable Scope:**

- The scope behavior for const is similar to let.
- The key difference lies in the immutability of const variables.
- Once assigned, their value cannot be changed.
- However, remember that const does not make objects or arrays immutable; it only prevents the reassignment of the variable itself.

## **🌟 Pros and Cons: Choosing the Right Variable 🌟**

## **var:**

Pros:

- The function-level scope can be advantageous in certain scenarios.
- Compatibility with older JavaScript versions.

Cons:

- Unpredictable behaviour due to hoisting and function-level scoping.
- Increased potential for bugs and unintended variable sharing.

## **let:**

Pros:

- Block-level scope provides more predictable and manageable code.
- Helps prevent accidental variable sharing and promotes encapsulation.
- Better error handling with Temporal Dead Zone (TDZ) restrictions.

Cons:

- Compatibility issues with older JavaScript versions.

## **const:**

Pros:

- Immutable variables ensure the initial value remains constant.
- Improves code readability by signalling the intention for constant values.
- Helps prevent accidental variable reassignment.

Cons:

- Requires careful consideration, as variables cannot be reassigned.
- Limited use for values that need to change dynamically.

**Conclusion:**

Congratulations on completing this thrilling adventure through the realms of variables in JavaScript! We explored var, let, and const, learned about their scopes, and discovered their pros and cons. Remember, choosing the right variable depends on the context and requirements of your code.

### **Who Am I?**

I’m Aswin Barath, a Software Engineering Nerd who loves building Web Applications, now sharing my knowledge through [Blogging](https://medium.com/techsoftware) during the busy time of my freelancing work life. Here’s the link to all of my socials categorized by platforms under one place: https://linktr.ee/AswinBarath

### **Join me to learn JavaScript!**

Checkout the **[JavaScript Roadmap Series](https://dev.to/aswin2001barath/series/24169)** where my mission is to share my knowledge on JavaScript: https://dev.to/aswin2001barath/series/24169

Learn what I know about JavaScript from any of my favourite knowledge sources:

- [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript)
- [W3Schools JavaScript Tutorial](https://www.w3schools.com/js/default.asp)
- [Complete Web Developer Course](https://dev.to/aswin2001barath/the-complete-web-developer-in-2022-zero-to-mastery-5dm1)
- [Junior to Senior Developer Course](https://dev.to/aswin2001barath/junior-to-senior-developer-roadmap-477p)
- [Top 5 JavaScript Courses on Udemy](https://dev.to/aswin2001barath/top-5-javascript-courses-on-udemy-is-it-worth-it-3523)
- [JavaScript Roadmap — The Basics: Event](https://youtu.be/ry8i5Qam7RI)
- [FreeCodeCamp **Front End Development Libraries**](https://www.freecodecamp.org/learn/front-end-development-libraries/)
- [FreeCodeCamp **Back End Development and APIs**](https://www.freecodecamp.org/learn/back-end-development-and-apis/)

### **Keep Learning**

So, keep coding, keep exploring, and always embrace the fun and creativity that JavaScript brings. May the force of JavaScript be with you as you continue your quest to conquer the web! 🚀

Now, go forth, young Jedi, and may your JavaScript adventures be filled with laughter, joy, and endless lines of epic code! May the code be with you! ✨

**Thank you** so much for reading my blog🙂.