Variables: Var, Let, Const - JavaScript Basics

ianferrier777

Ian Ferrier

Posted on July 1, 2022

Variables: Var, Let, Const - JavaScript Basics

Please note, for any of my dev blog posts, I am open to feedback and will make changes so long as I'm still active and can notice the changes. My brain isn't always screwed in all the way, all the time so I may not notice change requests. If you're new, pay attention to any comments that may be correcting information or adding necessary knowledge to this topic. The comments are welcome to more advanced knowledge of the topic or more information to topics related to this topic.

Why use variables?

Basic reason:

  • A variable is a place where you can store a value. You can make a variable called firstName and give it the value of 'Tom'.
  • It's like a box that stores what the value of something is.
  • Lets say we put your first name into the figurative box, the value of the figurative box will be your first name.
  • Imagine a program as sophisticated as everything you have to do to move from one home to another home. If you didn't label your boxes, you would regret that moving into the new home right? Heck you may even regret that moving everything into the transportation you are using! What if I stacked a bunch of heavy, robust stuff on a box I thought was full of heavy, robust stuff but actually was a box containing fragile stuff like glass kitchenware. Oopsies.
  • In the most basic use case, we're giving something a label.

Another basic reason: give a reusable value a name and keep code clean

  • Would you want to spell out (or copy and paste) "supercalifragilisticexpialidocious" every time I needed this in my code for some value? That would bring unnecessary and undesirable redundant code. We want reusable code. Always think about ways to make code reusable.
  • Would you want to have this sophisticated looking word repeated every time its needed in the code? I would hope not, that would make my eyes want to cry. It looks gross.
  • Lets take a look at using a variable to contain "supercalifragilisticexpialidocious" using the var keyword.
var longWord = 'supercalifragilisticexpialidocious';
console.log(longWord);
alert(longWord);
Enter fullscreen mode Exit fullscreen mode
  • See how nice that is? We eliminate the horrendously ugly value of "supercalifragilisticexpialidocious" (fun to say, hard to look at) and we've made it reusable. Let's see what it would look like without the variable.
console.log('supercalifragilisticexpialidocious');
alert('supercalifragilisticexpialidocious');
Enter fullscreen mode Exit fullscreen mode
  • See? Looks gross. And redundant. And yes writing the variable name is redundant, but it's much better than writing the value multiple times.
  • Another reason why this COULD be bad is that you're stating a value (the same exact value) twice in the program. I'm not entirely sure if Javascript will eat up more memory in this case rather than using the value of a single variable. It may not be the case, but some programming languages may do this from what I have seen. This bullet point is just a thought, not a fact.

Intermediate reason: A single "spot" to point to reference for a "spot" that experiences change.

  • Pardon the reason being a bit hard to understand. Hopefully I can clear it up.
  • Lets say you need to add some values to a count one at a time. I need some way to track this count. Let's take a look:
var count = 0;
count = count + 1; // Yes I'm aware there is shorter ways to do this.
count = count + 1;
count = count + 40;
Enter fullscreen mode Exit fullscreen mode
  • We've changed the value of count from what it originally was. By the end of this code, the count will not be 0, it will be 42 (Answer to life, the universe, and everything. Always remember to bring your towel).
  • Programs will use a variable to change and manipulate a value to get a desired end result.

What the heck are let and const?

  • Yeah! These two keywords are in the title, what do they do?
  • Simple answer: they are two other ways to make a variable. But they have special powers. var has many problems, but it's still needed since every browser hasn't quite caught up to the times with the more recent "versions" of JavaScript.

JavaScript: Brief variable keyword history.

  • The initial decision makers of the earlier "versions" of JavaScript wanted weird things to apparently make JavaScript easier. In my opinion they actually managed to make things more difficult.
  • var was the keyword these decision makers wanted for making variables.
  • The problem with var in a very brief description is when you declare a variable with var, var variables can be accessed outside of areas you would expect them to exist. Lets say you have a home with a security system inside. You don't want the whole world to know what your security system is. Well in some weird cases using var allowed for the outside to get access to that information (find out if you have a security system) or just access the variable itself (not the value) which means they could change that variable. Imagine if someone could just change the security system you own. Poof magic, you no longer have SimpliSafe, you have ADT. Absurd to think about but that's the general gist.
  • let and const come to the rescue! These two variable keywords don't bleed out into unusual areas causing the leaks we described var potentially having. They are "block scoped", which basically in our security system variable for inside a home, that security system stays inside the "scope" of the home. It's not leaking out. Stays right in there.

let and const in action

  • let allows us to also change and manipulate variable values much like var. It can be used the counting code snippet above in place of var without issue.
  • const on the other hand blocks you from manipulating the value of something at all (to an extent). It's a constant. If you needed to get something on a wall in an exact location, you would probably use a wall, floor, and/or ceiling. A constant plane. Its plane of existence does no change. Unless you start breaking any of these things or these might be curved or not exactly straight, BUT for this example, let's just think of flat surfaces. You can't suddenly bring the wall 2 feet towards the center of the house (not easily at least). - const variables are mainly used to assign a constant value. Maybe you have some function that makes a complicated evaluation according to the values you give it to solve for. When you get the solution, you may assign that value to a variable and not want it changed. You would use const in this case. They serve a great purpose for "Read Only" values. Once you make the value, all you can do is read it.
  • BUT const doesn't prevent you from changing "stuff" within reference type values. If I assign a list to a const variable, I could still change an item on that list. There are ways to protect this from happening, but in const's default state, you can change reference type values assigned to a const variable.
  • Once the value of a const is assigned, you're not going to be able to change what it is. I can't change a const variable with a reference type value to another reference type value. const does protect that from happening. But it does not (as previously mentioned) prevent a reference type value assigned to the const from being manipulated.
  • If you use a primitive type value with const, "that sucker ain't changin'" (pardon my non-proper lingo). If it's a number type value with the value of 10, then it's going to stay 10.

Basic examples of let and const

let count = 0;
count = count + 1;
count = count + 1;
count = count + 40;
// Still becomes 42.
Enter fullscreen mode Exit fullscreen mode
const count = 0;
count = count + 1;
/*
This is going to throw an error saying you can't do this along
with the following lines attempting to change the count.
"const".
*/
count = count + 1;
count = count + 40;
// In the end, count is gonna be zero. Can't change it.
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
ianferrier777
Ian Ferrier

Posted on July 1, 2022

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

Sign up to receive the latest update from our blog.

Related