Understanding Variables in JavaScript: The Var, Let, and Const Adventure!

aswinbarath

Aswin Barath

Posted on August 21, 2023

Understanding Variables in JavaScript: The Var, Let, and Const Adventure!

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:

var name = "John";
function greet() {
  if (true) {
    var name = "Jane";
    console.log("Hello, " + name + "!");
  }
  console.log("Goodbye, " + name + "!");
}
greet();
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, Jane!
Goodbye, Jane!
Enter fullscreen mode Exit fullscreen mode

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:

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

Output:

3
2
1
Blast Off!
Enter fullscreen mode Exit fullscreen mode
  • 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:

const pi = 3.14159;
pi = 3.14; // Oops! We can't do that.
console.log(pi);
Enter fullscreen mode Exit fullscreen mode

Output:

TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode
  • 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:
  2. As we saw earlier, var has function-level scope.
  3. It means that a variable declared with var is accessible throughout the entire function, regardless of where it’s declared.
  4. Let’s have another example:
function printNumbers() {
  for (var i = 1; i <= 5; i++) {
    setTimeout(function () {
      console.log(i);
    }, i * 1000);
  }
}
printNumbers();
Enter fullscreen mode Exit fullscreen mode

Output:

6
6
6
6
6
Enter fullscreen mode Exit fullscreen mode

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:
function printNumbers() {
  for (let i = 1; i <= 5; i++) {
    setTimeout(function () {
      console.log(i);
    }, i * 1000);
  }
}
printNumbers();
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

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 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 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:

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🙂.

💖 💪 🙅 🚩
aswinbarath
Aswin Barath

Posted on August 21, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related